C++ Do While Loop
The do/while loop is a close cousin of the while loop with one important twist: it runs the body first and checks the condition afterward. That guarantees the loop body always runs at least once, which is perfect for things like menus and prompts where you want to show something before deciding whether to repeat.
The do/while loop
With do/while, the code inside the do block executes, and only then is the condition tested. If it is true, the loop goes around again. Because the check happens at the bottom, the body is guaranteed to run one time no matter what.
Basic do/while
#include <iostream>
using namespace std;
int main() {
int i = 0;
do {
cout << i << "\n";
i++;
} while (i < 5);
return 0;
}Runs at least once
The example below starts with a value that fails the condition immediately. A plain while loop would print nothing, but the do/while still prints once because the body runs before the test.
The body always runs once
#include <iostream>
using namespace std;
int main() {
int i = 10;
do {
cout << "Value is " << i << "\n";
i++;
} while (i < 5);
cout << "Finished\n";
return 0;
}- Use do/while when the body must run at least one time.
- It is a natural fit for menus, prompts, and input validation.
- The condition is written at the end, after the closing brace.
In short, choose while when you might skip the loop entirely, and choose do/while when you always want at least one pass before deciding whether to repeat.