capypad
0 day streak
cpp / beginner
Snippet

While Loops: Iteration with Unknown Count

A while loop repeats code as long as a condition remains true. The condition is checked BEFORE each iteration, so the loop body might never execute if the condition is initially false. In this example, countdown starts at 5 and decreases until it reaches 0.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
 
int main() {
int countdown = 5;
while (countdown > 0) {
std::cout << countdown << std::endl;
countdown = countdown - 1;
}
std::cout << "Liftoff!" << std::endl;
return 0;
}
Breakdown
1
while (countdown > 0) {
Loop condition - repeats while countdown is greater than 0
2
countdown = countdown - 1;
Decrements countdown by 1 each iteration