Next:do-while loopUp:DecisionsPrevious:while loop

for loop

Commonly used for a fixed number of iterations.

The syntax is

   for (expr1; expr2; expr3)
      statement
Any or all of the three expressions can be omitted, but the semi-colons must remain. If expr2 is not present, it is assumed to be true.

What happens in general is as follows:

   expr1;

   while (expr2)
      {
      statement
      expr3;
      }
and so expr2 must initially be true for the statement to be executed.

In practice, the commonest use has expr1 initializing a loop counter; expr2 checking if the loop has finised; expr3 updating the loop counter, as follows.

Example

   int x, total;

   total= 0;

   /* Loop ten times */
   for (x= 1; x<=10; x= x + 1)
      total= total + x;


Next:do-while loopUp:DecisionsPrevious:while loop


maspjw@

Tue Sep 27 15:29:34 BST 1994