Next: Example for statement: Print Up: Introduction to C++ Programming Previous: Exercises

The for statement

 

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:

  1. Initialisation - initialise the control variable i (i = 1).
  2. Test expression - evaluate the truth value of an expression (i <= 10).
  3. Update expression - update the value of the control variable before executing the loop again (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:

for ( initialise ; test ; update )
statement
which executes the initialise statement when the 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.



Subsections

Next: Example for statement: Print Up: Introduction to C++ Programming Previous: Exercises