C++ While Loop
Introduction to While Loops
The while
loop executes a block of code repeatedly as long as the specified condition evaluates to true.
It is especially useful when the number of iterations is not known beforehand and depends on runtime conditions.
Basic Syntax
while (condition) {
// code to execute repeatedly
// while condition is true
}
Simple Example
#include <iostream>
int main() {
int count = 1;
while (count <= 5) {
std::cout << "Count: " << count << '\n';
++count; // update condition to avoid infinite loop
}
return 0;
}
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Infinite Loops
A while loop will become infinite if its condition never becomes false. This can be intentional for servers or background tasks, but must be carefully controlled:
#include <iostream>
int main() {
while (true) {
std::cout << "Running...\n";
// if (should_stop()) break; // add an exit condition when appropriate
}
}
Loop Control
Special statements can alter the flow of a while loop:
#include <iostream>
int main() {
int num = 0;
while (num < 10) {
++num;
if (num == 5) continue; // skip printing 5
if (num == 8) break; // exit loop at 8
std::cout << num << ' ';
}
return 0;
}
1 2 3 4 6 7
Statement | Effect |
---|---|
break | Exits the loop immediately |
continue | Skips the rest of the current iteration and continues with the next |
return | Exits the entire function, ending the loop as well |
While vs Do-While
A do-while
loop checks its condition after executing the body, so it runs at least once:
#include <iostream>
int main() {
int n = 0;
do {
std::cout << "Executed once even if condition is false\n";
} while (n != 0);
}
Common Patterns & Pitfalls
- Off-by-one errors: double-check boundary conditions (e.g., <=
vs <
).
- Make sure the loop body eventually changes the condition; otherwise you’ll loop forever.
- Avoid using floating-point equality in loop conditions due to rounding (prefer counters or tolerances).
// Input-driven loop pattern
// int x; while (std::cin >> x) { /* process x */ } // ends on EOF/invalid input