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 ();
 } 

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

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