The While Loop in C++
The while
loop allows you to execute a block of code repeatedly as long as a specified condition remains true. It's useful when the number of iterations is not known beforehand.
Syntax of the while
Loop
while (condition) {
// Code to execute
}
Example: Using the while
Loop
#include <iostream>
int main() {
int count = 1;
while (count <= 5) {
std::cout << "Count: " << count << std::endl;
count++;
}
return 0;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Explanation: The loop continues to execute as long as count
is less than or equal to 5. The variable count
is incremented in each iteration.
Key Takeaways
- The
while
loop checks the condition before each iteration. - If the condition is false initially, the loop body may not execute at all.
- Ensure the loop has a condition that will eventually become false to prevent infinite loops.