capypad
0 day streak
cpp / beginner
Snippet

While Loops: Repeating Code

A while loop repeatedly executes a block of code as long as its condition remains true. The loop checks the condition before each iteration, so if the condition is false from the start, the code inside never runs. In the first example, count starts at 1 and increments until it reaches 5. The second example demonstrates a countdown that decrements by 2 each iteration, showing how while loops can control more complex sequences.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
 
int main() {
int count = 1;
while (count <= 5) {
cout << "Iteration " << count << endl;
count++;
}
cout << "\nCountdown: " << endl;
int countdown = 10;
while (countdown > 0) {
cout << countdown << " ";
countdown -= 2;
}
cout << "GO!" << endl;
return 0;
}
Breakdown
1
while (count <= 5) {
Loop header checking if count is less than or equal to 5 before each iteration
2
count++;
Increment operator increasing count by 1 each iteration - crucial to avoid infinite loop
3
countdown -= 2;
Compound assignment subtracting 2 from countdown each iteration
4
while (countdown > 0) {
Second while loop with different condition creating countdown effect