Next: Example for statement: Print
Up: Introduction to C++ Programming
Previous: Exercises
Frequently in programming it is necessary to execute a statement a
fixed number of times or as a control variable takes a sequence of values.
For example consider the following use of a while
statement to output
the numbers 1 to 10. In this case the integer variable i
is
used to control the number of times the loop is executed.
i = 1; while (i <= 10) { cout << i << endl; i++; }
In such a while loop three processes may be distinguished:
i
(i = 1
).i <= 10
).i++
).These concepts are used in the for statement which is designed for the case where a loop is to be executed starting from an initial value of some control variable and looping until the control variable satisfies some condition, meanwhile updating the value of the control variable each time round the loop.
The general form of the for
statement is:
which executes the initialise statement when thefor (
initialise;
test;
update)
statement
for
statement is first entered, the test
expression is then evaluated and if true the loop
statement is executed followed by the update statement.
The cycle of (test;execute-statement;update) is then continued until the
test expression evaluates to false,
control then passes to the next statement in the program.