Dec 16, 2011

For loops in C + +


Well, we understood a little theory of cycles in c + +, now let's practice on how to use the for loop.

How to make a cycle in C + +?

 # Include <stdio.h>
 # Include <conio.h>
 int main ()
 {
   int x = 0;
   for (x = 0, x <= 5, x + +)
   {
     printf ("% d", x);
   }
   getch ();
 }
 / / This program will display 0 1 2 3 4 5 
You see, we need a unique variable for the cycle (in this case 'x') and it starts with the word for, its syntax is:
for (variable = start-of-cycle, a condition-that-tells-the-end, increasing x)
By parts:
  • x = 0 -> Indicates the start of the cycle. It can be any variable and any starting value.
  • x <= 5 -> Indicates the end of the cycle. When the condition no longer met the cycle ends.When the cycle is less than or equal to 5 the cycle ends.
  • x + + -> Indicates the variable 'x' increases one by one. To increase two and two: x + = 2, three: x + = 3.
Another example, the multiplication table of 2 in C + +:
 # Include <stdio.h>
 # Include <conio.h>
 int main ()
 {
   int c = 0;
   for (c = 1, c <= 10, c + +)
   {
     printf ("2 x% d =% d \ n", c, 2 * c);
   }
  getch ();
 } 

Get random numbers in C + + (rand, srand)


It happens very often, when you've mastered all that to ask for and store data, now your teacher asks you to generate random numbers your software to automate the process of completing arrangements and all that.
So the first thing we have to do is include the library:
#include<stdlib.h>
Then initialize the random numbers including this:
srand(time(NULL));
* Update: why not throw some mistake with IDE's time function. Well just use the library time.h:
#include<time.h>
Then save the random number somewhere:
num=rand();
That's basically. To set the random number range can do several things.
Random number between 0 and 50:
num=rand()%51;
Random number between 1 and 100:
num=1+rand()%(101-1);
Random number between 250 and 420:
num=250+rand()%(421-250);
In general form is:
variable = limite_inferior + rand() % (limite_superior +1 - limite_inferior) ;
So a program that displays 10 random numbers between 1 and 10 would read:
 Stdlib.h
 # Include <iostream>
 using namespace std;

 int main ()
 {
     int num, c;
     srand (time (NULL));
     for (c = 1, c <= 10, c + +)
     {
         num = 1 + rand ()% (11 - 1);
         court <<num <<"";
     }
     cin. get ();
 } 

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes