capypad
0 day streak
cpp / beginner
Snippet

Do-While Loops: Execute First, Check Later

A do-while loop guarantees that the body executes at least once, because the condition is checked AFTER the first execution. This is useful when you need to prompt the user for input before knowing whether to continue. The loop continues until the user enters 0.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
 
int main() {
int userInput;
do {
cout << "Enter a number (0 to exit): ";
cin >> userInput;
cout << "You entered: " << userInput << endl;
} while (userInput != 0);
cout << "Goodbye!" << endl;
return 0;
}
Breakdown
1
do {
Starts the do-while loop - body executes immediately without checking condition first
2
cin >> userInput;
Reads integer input from the user and stores it in userInput
3
cout << "You entered: " << userInput << endl;
Displays the value that was just read from input
4
} while (userInput != 0);
Condition follows the body - loop repeats if userInput is not 0, otherwise exits
5
cout << "Goodbye!" << endl;
Executes after loop exits, signaling the program is ending