The do-while loop

Occasionally it is more appropriate to check the loop-terminating condition after the body has executed. In this case, the do-while loop is useful. This is defined as:

do {
      body
} while ( condition );

where

  • condition is a boolean expression;
  • body is zero or more statements;
  • The do-while loop executes the code in body, then repeatedly executes it as long as the condition expression evaluates to true, evaluating condition after each execution of body.

Here's an example that keeps rolling a pair of dice until a double is rolled.

do {
   dice.roll();
} while (!dice.isDoubles());

Note that the do-while loop always executes the body at least once, but the while loop may not execute the body at all.