[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Aggregation Up: Loops Previous: while, do

for

The `for' construction in C++ is very general. In its most common form it's much like for in other languages. The following loop starts with i set to 0 and carries on while i<5 is true, adding 1 to i each time round.

...
for(int i=0; i<5; i=i+1){ 
   something();
}
...

The general form of `for' is

for ([expression1]; [expression2]; [expression3])
     something();

where all the expressions are optional. The default value for expression2 (the while condition) is 1 (true). Essentially, the for loop is a while loop. The above for loop is equivalent to

...
expression1;         // initialisation
while (expression2){ // condition
   something();
   expression3;      // code done each iteration
};
...

E.g. the 2 fragments below are equivalent. `i' is set to 3, the loop is run once for i=3 and once for i=4, then iteration finishes when i=5.



for (int i = 3; i < 5; i=i+1)
   total = total + i;






int i = 3;
while(i < 5){
  total = total + i;
  i=i+1;
}




Within any of the above loop constructions, continue stops the current iteration and goes to the next and break stops the iterations altogether. E.g. in the following fragment 0 and 2 will be printed out.

...
int i=0;
while (i<5){
   if (i==1){
     i = i+1;
     continue;
   }
   if (i==3)
     break;
   printf("i = %d\n", i);
   i=i+1;
}
...

If you want a loop which only ends when break is done, you can use `while(true)' or `for(;;)'.


next up previous contents
Next: Aggregation Up: Loops Previous: while, do
Tim Love
2001-07-05