capypad
0 day streak
cpp / beginner
Snippet

While Loops: Repeating Actions

A while loop repeats a block of code as long as a condition remains true. The condition is checked BEFORE each iteration, so if it starts false, the loop never runs. Here we countdown from 5 to 1, then print Liftoff!

snippet.cpp
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
int countdown = 5;
Initialize counter variable before loop starts
2
while (countdown > 0) {
Loop condition - keeps running while countdown is positive
3
countdown = countdown - 1;
Decrement counter to eventually exit loop