cpp / beginner
Snippet
While Loop: Repeating Until a Condition is False
A while loop repeats code as long as its condition is true. The condition is checked BEFORE each iteration. If the condition is initially false, the loop body never executes. Always ensure the condition eventually becomes false to avoid an infinite loop.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>int main() {int count = 1;while (count <= 5) {std::cout << "Count is: " << count << std::endl;count = count + 1;}return 0;}
Breakdown
1
int count = 1;
Initializes a counter variable to 1 before the loop starts
2
while (count <= 5) {
Checks if count is less than or equal to 5; loop continues while true
3
std::cout << "Count is: " << count << std::endl;
Prints current value of count each iteration
4
count = count + 1;
Increments count by 1 to eventually end the loop