Next: Example for statement: Print Up: The for statement Previous: The for statement

Example for statement: Print 10 integers

The equivalent for statement to the while statement in section 16.1 is

for (i = 1; i <= 10; i++)
   cout << i << endl;
Download program.
which initially sets i to 1, i is then compared with 10, if it is less than or equal to 10 then the statement to output i is executed, i is then incremented by 1 and the condition i <= 10 is again tested. Eventually i reaches the value 10, this value is printed and i is incremented to 11. Consequently on the next test of the condition the condition evaluates to false and hence exit is made from the loop.



Next: Example for statement: Print Up: The for statement Previous: The for statement