The while loop operator is used when it is required to repeat some execution sequence for several times (or not once). Such task can be resolved also with the help of another loop operator— operator for.
For loop operator format:
for ( expression 1; expression 2; expression 3 )
operator;
The execution of the for loop operator starts with the calculation of the «expression 1». It is a kind of the loop initialization, which is implemented only once and precedes the following operations.
Then the « expression 2» is evaluated. If it is true the «operator» is executed. Then the « expression 3» is evaluated. The first loop iteration is over. The second iteration starts again with the evaluation of the « expression 2». If it is true, then the «operator» is executed. Then the « expression 3» is evaluated again and this repeats as long as the «expression 2» is true. If the « expression 2» is false at the first iteration the loop will never be executed.
If we consider carefully the logic of the for loop operator we may notice that it corresponds fully to the following portion of the code where the while loop operator is used:
expression 1;
while (expression 2 )
{
operator;
expression 3;
}
In the previous article we considered an example of how the while loop operator is used :
int i = 0;
while ( i < 9 )
{
Print( i );
i++;
}
Print ("Done");
This example can be rewritten using the for loop operator:
int i;
for (i = 0; i < 9; i++)
Print( i );
Print ("Done");
It won’t be a mistake if any of the three or all the three statements in the for loop operator are omitted, but semicolons (;) that separate them mustn’t be omitted. If omitted the «expression2» is taken to always be true.
«Expression1» and «expression3» may consist of several expressions united by a comma. In such a case each expression is evaluated from left to right:
for (i = 0, j = 0; i < 9; i++)
Print ( "i = ", i, " j= ", j );
Next article: "
Operators Break and Continue"