#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.

Advertisement