Loading lessons...
While Loops
While Loops
A while loop repeats code as long as a condition stays true.
The basic form
while (condition) {
// run again and again while condition is true
}
A real example
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
Output:
0
1
2
3
4
The three parts
- The condition checks before each round.
- The body does the work.
- The update (
i++) moves toward stopping.
Endless loop danger
If nothing changes the condition, the loop never stops:
while (1) { // always true!
printf("forever");
}
TL;DR
while (condition) { ... }repeats while true.- The condition is checked before each run.
- The body must eventually make the condition false.
- Use
i++type updates to count safely.