The do-while loop
- C++ course
- Beginner
- Lesson 44/116
- 4 min
Learn loops that run at least once with do-while.
The do-while loop
When you want to run the body at least once you use the do-while loop. Its form is do { ... } while (condition);; the body runs first, then the condition is checked.
For example int n = 0; do { std::cout << n; n++; } while (n < 3); prints 0, 1 and 2. The difference from while is that the condition is checked at the end, so the body always runs at least once. This makes it ideal for asking the user at least one question.
do-while vs while
The key difference between do-while and while is where the condition is checked. In while it is checked at the top, in do-while at the bottom. Because of this, do-always runs its body at least once.
This matters for menu display: show the options once, get the answer, ask again if invalid. The pattern do { ... } while (choice != 0); shows the menu again until option 0 is entered.
Practice Print once (do-while)
The n variable is set to 5. Write a do { std::cout << n; n++; } while (n < 3); loop. Even though the condition is false, the body runs once; the output must be 5.
Starter code
#include <iostream>
int main() {
int n = 5;
// Print with do-while
return 0;
}Sample solution
#include <iostream>
int main() {
int n = 5;
do {
std::cout << n;
n++;
} while (n < 3);
std::cout << std::endl;
return 0;
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the do-while closing
do {
std::cout << n;
n++;
} ____ (n < 3);
do {
std::cout << n;
n++;
} while (n < 3);
Explanation: do-while ends with while and a semicolon.
2 At least how many times does a do-while loop run?
do { ... } while (cond);- 1 time Correct answer
- 0 times
- 2 times
- Forever
Explanation: The body runs first; even if the condition is false it loops at least once.
3 Match each do-while part to its role
| Term | Meaning |
|---|---|
do |
Starts the body |
{ ... } |
Loop body |
while |
Asks the condition |
(n < 3) |
Continue condition |