capypad
0 day streak
cpp / beginner
Snippet

Do-While Loop: Guaranteed First Execution

The do-while loop always executes its body at least once before checking the condition. Unlike a regular while loop that checks first, do-while guarantees the code runs once regardless of whether the condition is true or false initially.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
 
int main() {
int count = 0;
do {
cout << "Count: " << count << endl;
count++;
} while (count < 3);
return 0;
}
Breakdown
1
do { ... } while (condition);
Body executes first, then condition is checked; semicolon required after while