C++ While Loop
A C++ while loop checks its condition before every pass, so the body may never run at all if the condition starts out false. Instead of writing the same line ten times, you write it once and let the loop do the counting. This is one of the first big steps from writing straight-line programs to writing programs that actually work for you.
The while loop
The while loop checks a condition before every pass through the loop body. As long as that condition evaluates to true, the code inside the braces runs. The moment the condition becomes false, the loop stops and your program continues with whatever comes after it.
Counting from 0 to 4
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
return 0;
}Notice the three moving parts: we start with i = 0, we test i < 5 before each pass, and we increase i with i++ inside the loop. If you forget to change i, the condition would stay true forever.
How the condition is checked
- The condition is tested first, before the body ever runs.
- If it is false right away, the loop body runs zero times.
- After each pass, control jumps back to the top and the condition is tested again.
- The loop ends only when the condition becomes false.
A loop that may run zero times
#include <iostream>
using namespace std;
int main() {
int count = 10;
while (count < 5) {
cout << "This never prints\n";
count++;
}
cout << "Done\n";
return 0;
}Use a while loop when you do not know in advance exactly how many times you need to repeat, but you do know the condition that should keep it going, such as reading numbers until the user types zero.
Exercise: C++ While Loop
What happens if a while loop's condition is false the very first time it is checked?