C++ tutorial: for
A 'for' loop typically repeats a fixed number of times
The 'for' loop is similar to the while loop, but formalizes the sorts of operations
that normally control a loop. The general structure of a 'for' loop is shown
below:
for (start_statements; condition; loop_statements)
{
statment1;
statment2;
// more statements...
}
'start_statements' is the set of statements that are executed before the loop
begins. These typically define the variables used in the loop and their unitial values.
'condition' is the condition under which the loop will continue to run; this is
exactly the same as the condition in 'while' loop.
'loop_statements' is the set of statements that is executed at the end of each
turn of the loop.
This may sound complicated, but almost all practical uses of 'for' are for implementing
a simple loop that executes a fixed number of times. The usual format of such a
loop is:
for (int i = 1; i <= N; i++)
{
statment1;
statment2;
// more statements...
}
This loop will repeat 'N' times, because it starts by setting 'i' to 1, and
continues while 'i' is less than or equal to 'N'.
Exercise: re-write 'box1.cpp' so that it achieves the same result using a 'for'
loop
|