![[Dept of Engineering]](http://www.eng.cam.ac.uk/images/house_style/engban-s.gif)
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(;;)'.