#163 – Iterating Using the for Loop

The for statement allows executing a block of code a fixed number of times.

You could use a while loop to execute a block of code a fixed number of times:

            int i = 1;
            int sum = 0;

            // Add up numbers 1-10
            while (i <= 10)
            {
                sum += i;
                i++;
            }

You can do this a little more conveniently using a for loop.

            int sum = 0;

            // Add up numbers 1-10
            for (int i = 1; i <= 10; i++)
                sum += i;

The expression after the for keyword includes three clauses, separated by a semicolon:

  • The initialization clause specifies variables to initialize before the loop starts executing
  • The condition clause specifies the conditions under which the loop continues to execute
  • The iteration clause specifies an operation to perform after executing the body of the loop
Advertisement

#162 – do/while Loop Executes At Least Once

Similar to the while loop is the do/while loop, which executes at least once and tests a conditional expression at the end of the loop to determine whether to continue iterating.

In the example below, we first make one pass through the loop, raking leaves.  After executing the loop once, we count the remaining leaves on the lawn to determine if we need to continue raking and bagging.

            uint numLeavesOnLawn;

            // Rake first, count leaves later
            do
            {
                RakeLeaves();
                FillNextBag();
                numLeavesOnLawn = CountLeaves();
            } while (numLeavesOnLawn > 50);

Like the while loop, you can exit a do/while loop on break, goto, return or throw statements.

Like the while loop, you can proceed immediately with the next iteration using the continue statement.