cpp / beginner
Snippet
While Loops: Repeating Until a Condition is Met
A while loop repeatedly executes a block of code as long as a condition remains true. The condition is checked BEFORE each iteration, so if it's false from the start, the loop body never runs. Here, we start with countdown at 5, and each iteration decreases it by 1 until it reaches 0, at which point the condition becomes false and the loop ends.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>using namespace std;int main() {int countdown = 5;while (countdown > 0) {cout << "Countdown: " << countdown << endl;countdown = countdown - 1;}cout << "Liftoff!" << endl;return 0;}
Breakdown
1
while (countdown > 0)
The loop condition - keeps running as long as countdown is greater than 0
2
cout << "Countdown: " << countdown << endl;
Prints the current countdown value with a descriptive label
3
countdown = countdown - 1;
Decreases countdown by 1 each iteration (same as countdown--)
4
cout << "Liftoff!" << endl;
After the loop ends, prints the final message
5
return 0;
Indicates successful program completion to the operating system