capypad
0 day streak
cpp / beginner
Snippet

While Loops for Conditional Repetition

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 body never executes. In this example, count starts at 0 and increments until it reaches 5, causing the condition count < 5 to become false and exit the loop.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
int main() {
int count = 0;
while (count < 5) {
std::cout << "Count is: " << count << std::endl;
count = count + 1;
}
std::cout << "Loop finished!" << std::endl;
return 0;
}
Breakdown
1
#include <iostream>
Includes the input/output stream library for console output
2
int main() {
Entry point of the program, returns an integer
3
int count = 0;
Declares an integer variable initialized to 0
4
while (count < 5) {
Loop continues while count is less than 5
5
std::cout << "Count is: " << count << std::endl;
Prints current count value to console
6
count = count + 1;
Increments count by 1 each iteration
7
}
Closing brace ends the while loop body
8
std::cout << "Loop finished!" << std::endl;
Prints completion message after loop exits
9
return 0;
Returns 0 to indicate successful program termination