cpp / beginner
Snippet
While Loops: Repeating Code While a Condition Is True
A while loop repeats a block of code as long as a specified condition evaluates to true. The condition is checked BEFORE each iteration, so if it's false initially, the loop body never executes. Here, count starts at 0 and increments by 1 each iteration until it reaches 5, at which point the condition becomes false and the loop exits. This is called a pre-test loop because the test happens before the code runs.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>int main() {int count = 0;while (count < 5) {std::cout << "Count is: " << count << std::endl;count = count + 1;}return 0;}
Breakdown
1
#include <iostream>
Include the input/output stream library for std::cout
2
int main() {
Main function where program execution begins
3
int count = 0;
Initialize a counter variable to 0
4
while (count < 5) {
Loop continues while count is less than 5
5
std::cout << "Count is: " << count << std::endl;
Print current value of count to console
6
count = count + 1;
Increment count by 1 each iteration
7
}
Closing brace ends the while loop body
8
return 0;
Exit the program successfully