12. Do Loops

The purpose of a do loop, also known as a do-while loop, is to repeat one or more statements. The primary difference between do loops and while and for loops, which will be looked at next, is that the statements in a do loop will always execute once and repeat if necessary.

General Form

The general form of a do loop is as follows:

do {
    loop-body
} while (test);

Some important points:

The statements in the loop body should be indented and left aligned to visually emphasize they are in the loop.

How a Do Loop Works

The steps taken when a do loop executes are as follows:

  1. The statements in the loop body are executed.
  2. The test is performed.
  3. If the test evaluates to true, go back to Step 1.
  4. If the test evaluates to false, execution of the loop ends then execution passes to the first executable statement following the do loop.

Given how a do loop works, here are a few additional points:

Example – Counter-Controlled Loop

The do loop that follows displays the word “Hello” three times. The loop is controlled by the counter variable which is initialized to zero and incremented each time the loop body executes.

int counter = 0;

do {
    std::cout << "Hello" << std::endl;
    counter++;
} while (counter < 3);

Step through the code by following the steps above.

Example – User-Controlled Loop

The example that follows shows a do loop being used to display multiples of four (i.e., 4, 8, 12, etc.). The code repeats until the user chooses to stop.

int current_value = 0;
char answer;

do {
    current_value += 4;
    std::cout << "Current value: " << current_value << std::endl;
    std::cout << "Display the next value (y/n)? ";
    std::cin >> answer;
} while (answer == 'y' || answer == 'Y');

Step through the code.