for

The for loop is like a while loop but it incorporates an initialisation and an action into the loop. The syntax is:

Example 7.5. for statement syntax

for(/* initialisation */ ; /* boolean expression */ ; /* action */)
    // Statement

The initialisation is a comma separated list of zero or more expressions optionally terminated by a variable declaration. Any variables declared in the initialisation are visible only in the scope of the loop. The action is also a comma separated list of zero or more expressions which will be evaluated after each iteration of the loop. Any of the three sections (initialisation, boolean expressiona and action) can be ommited. If the boolean expression is ommited then it is as if the boolean expression true is used.

The for loop is really just syntactic sugar; it is equivalent to a while loop as illustrated below:

Example 7.6. Translation of a for loop into a while loop

The code below:

for(i = 7, int j = 42;  i < j;  i++, j--)
    print(i);

...is equivalent to this:

{
    i = 7;
    int j = 42;

    while(i < j)
    {
        print(i);
        i++;
        j--;
    }
}