The while and the do..while loops are used when the number
of iteration(the number of times the loop body is executed)
is not known. The for loop is used for fixed iterations.
The following program illustrates the usage of the for loop:
//This program calculates the square of the first ten
for(iVar = 1; iVar <= 10; iVar++)
The output of Program 2.4 is:
1 4 9 16 25 36 49 64 81 100
The for statement consists of the keyword for, followed by
parentheses containing three expressions, each separated by
These three expressions are the initialization expression,
test expression and the increment/decrement(re-initialization)
The general format of a for loop is:
for(initialization; test; re-initialization)
In the statement,
for(iVar = 0; iVar <= 10; iVar++)
iVar = 0 is the initialization expression, iVar <= 10 is the
test expression, and iVar++ is the increment expression.
The initialization expression is executed only once when the
loop first starts. It gives the loop variable an initial
The test expression involves relational operators. It is
executed each time through the loop before the body of the
loop is executed. If the test expression is true, the loop
is executed, and if it is false, the control passes to the
statement following the for loop.
The increment/decrement expression is always executed at the
end of the loop, after the loop body.
The body of the loop is enclosed within braces and is not
executed if the for statement is followed by a semicolon.
For example, in the following statement is followed by a
semicolon. For example, in the following statement:
for(iVar = 0; iVar <= 10; iVar++);
the body of the for loop is not executed.