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 words
doandwhileare keywords. - The statements to repeat should be placed within the braces indicating the loop body.
- The test is a Boolean expression or compound condition, as needed.
- The braces, parentheses, and semicolon are required.
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:
- The statements in the loop body are executed.
- The test is performed.
- If the test evaluates to
true, go back to Step 1. - If the test evaluates to
false, execution of the loop ends then execution passes to the first executable statement following thedoloop.
Given how a do loop works, here are a few additional points:
- The statements in the loop body execute at least once.
- As long as the test evaluates to
true, the statements in the loop body will repeat. - The keywords
doandwhiledo not perform any action. They only indicate the beginning and end of the loop. - The test is referred to as a posttest because it is first performed after the loop body statements execute.
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.
- What is counter’s value when execution of the loop ends?
- Why is this an example of a definite loop?
- What would happen if the statement
counter++;was accidentally forgotten?
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.
- What type of variable is
current_value? - Why does the test include both lowercase and uppercase versions of the letter ‘y’?
- Why is this an example of an indefinite loop?