A typical loop uses a counter that is initialized, tested by the controlling expression and reinitialized at the end of the loop.
int count = 1; // Initialization while( count <= 10) // Controlling { // expression cout << count << ". loop" << endl; ++count; // Reinitialization }
In a for loop statement the elements that control the loop can be found in the loop header.
The above example can also be expressed as a for loop:
int count; for( count = 1; count <= 10; ++count) cout << count << ". loop" << endl;
Any expression can be used to initialize and reinitialize the loop.
A for loop has the following form:
for( expression1; expression2; expression3 )
statement
Any of the three expressions in a for statement can be omitted.
You must type at least two semicolons. The shortest loop header is therefore:
for(;;)
This statement causes an infinite loop, since the controlling expression is assumed to be true if expression2 is missing. In the following
for( ; expression; )
the loop header is equivalent to while(expression). The loop body is executed as long as the test expression is true.