Loading lessons...
While Loop
While Loop
Loops let the same block of code run over and over. The while loop keeps repeating while its condition stays true.
The shape
while (condition) {
// repeated statements
}
- Check the condition first.
- If it is true, run the block.
- Then go back and check again.
- When the condition is false, the loop ends.
An example
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << endl;
i++;
}
return 0;
}
This prints 0, 1, 2, 3, 4. The key is the i++ at the end of the body. It changes i so that after five trips the condition i < 5 finally fails.
The infinite loop danger
If nothing in the body ever changes the condition, the loop runs forever. That is an infinite loop, and it usually freezes your program.
int i = 0;
while (i < 5) {
cout << i << endl; // i never changes!
}
Always make the body push the loop towards its stopping point, for example by incrementing a counter. LearnCpp 8.8 calls this the most common loop bug.
TL;DR
while (condition) { ... }repeats while the condition is true.- The condition is checked before each trip.
- Change the condition inside the body, or you get an infinite loop.
- Incrementing a counter is the most common way to end the loop.