cpp / beginner
Snippet
Do-While Loops: Execute Before Check
The do-while loop guarantees at least one execution of the loop body. The condition is checked AFTER each iteration, unlike while loops which check first. This is useful when you need to prompt for input at least once.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>int main() {int guess;do {std::cout << "Enter a number: ";std::cin >> guess;} while (guess != 42);std::cout << "Correct!" << std::endl;return 0;}
Breakdown
1
do {
Starts the do-while loop, body executes first
2
} while (guess != 42);
Condition checked after body runs - loop repeats if condition is true