C While Loop
The while loop repeats a block of code as long as its condition remains true. The condition is checked before each iteration, so the body might never execute if the condition starts false.
A related loop, do...while, checks the condition after the body runs, guaranteeing the body executes at least once.
while (condition) {
// code
}
do {
// code
} while (condition);while loop
while evaluates its condition first; if true, the body runs, then the condition is checked again. This continues until the condition becomes false.
do...while loop
do...while runs the body first, then checks the condition. This guarantees the loop body executes at least once, which is useful for menus or input validation.
#include <stdio.h>
int main() {
int i = 0;
while (i < 3) {
printf("%d\n", i);
i++;
}
return 0;
}0
1
2The loop prints i and increments it until i is no longer less than 3.
#include <stdio.h>
int main() {
int i = 5;
do {
printf("%d\n", i);
i++;
} while (i < 3);
return 0;
}5do...while runs the body once even though the condition (i < 3) is false from the start.
Key points
- while checks its condition before running the body.
- do...while checks its condition after running the body.
- Forgetting to update the loop variable causes an infinite loop.
- Loop conditions must eventually become false to end the loop.
