capypad
0 day streak
cpp / beginner
Snippet

While Loop Repetition

A while loop repeats a block of code as long as its condition evaluates to true. The condition is checked BEFORE each iteration, so if it is false initially, the loop body never executes. Inside the loop, you must have code that eventually makes the condition false, otherwise you create an infinite loop. The countdown example shows a controlled loop that terminates when countdown 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: " << countdown << std::endl;
countdown--;
}
std::cout << "Liftoff!" << std::endl;
return 0;
}
Breakdown
1
while (countdown > 0) {
Condition checked before each iteration, loop runs while true
2
countdown--;
Decrements countdown, eventually making condition false
3
Liftoff!
Prints after loop condition becomes false