cpp / beginner
Snippet
Do-While Loops: Code That Runs At Least Once
The do-while loop is a post-test loop, meaning the code block executes first and the condition is checked afterward. This guarantees the loop body runs at least once, unlike a while loop which might not run at all if the condition starts false. This pattern is useful when you need to prompt for input before validating it, like a menu that should display at least one time.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>int main() {int userNumber;do {std::cout << "Enter a number (0 to exit): ";std::cin >> userNumber;std::cout << "You entered: " << userNumber << std::endl;} while (userNumber != 0);std::cout << "Goodbye!" << std::endl;return 0;}
Breakdown
1
#include <iostream>
Include iostream for input/output operations
2
int main() {
Program entry point
3
int userNumber;
Declare variable to store user's input
4
do {
Start of do-while loop - code runs before check
5
std::cout << "Enter a number (0 to exit): ";
Prompt user to enter a number
6
std::cin >> userNumber;
Read integer input from user
7
std::cout << "You entered: " << userNumber << std::endl;
Echo back the entered number
8
} while (userNumber != 0);
Condition checked AFTER execution - loop repeats if not 0
9
std::cout << "Goodbye!" << std::endl;
Printed after loop exits when user enters 0
10
return 0;
End program successfully