The statements in the for loop repeat continuously
for a specific number
of times.
The while
and do-while loops repeat until a certain condition is met. The for loop repeats until a specific count is met.
Use a for loop when the number of repetition is know, or can be
supplied by the user. The coding format is:
for(startExpression; testExpression;
countExpression)
{
block of code;
}
The startExpression is
evaluated before the loop begins. It is acceptable to
declare and assign in the startExpression
(such as int x = 1;). This startExpression
is evaluated
only once at the beginning of the loop.
The testExpression
will
evaluate to TRUE (nonzero) or FALSE
(zero). While TRUE, the body of the loop repeats. When the testExpression becomes FALSE,
the looping stops and the program continues with the statement immediately following the
for loop body in the program code.
The countExpression
executes after each trip through the loop. The count may
increase/decrease by an increment of 1 or of some other value.
Braces are not
required if the body of the for loop consists of only ONE
statement. Please indent the body of
the loop for readability.
CAREFUL: When a for
loop terminates, the value stored in the computer's memory under the looping
variable will be "beyond" the testExpression in the loop. It must be sufficiently large (or small) to
cause a false
condition. Consider:
for (x = 0; x <= 13; x++)
cout<<"Melody"; |
When this loop is finished,
the value 14 is stored in x. |
|