Sometimes you need to repeat something over and over until a condition changes. That's a loop. The while loop is the simplest — it keeps going as long as its condition is true.
The while Loop
Check the condition first. If it's true, run the body. Then check again. Repeat until false.
#include
int main() {
int i = 1;
while (i <= 5) {
printf("Count: %d\n", i);
i++;
}
return 0;
}
Try it Yourself →
How Condition Checking Works
The condition is evaluated before each iteration. If it's false from the start, the body never runs. That's why while is called a pre-test loop.
#include
int main() {
int i = 10;
while (i <= 5) {
printf("This won't print\n");
i++;
}
printf("Loop skipped because 10 > 5\n");
return 0;
}
Try it Yourself →
Infinite Loops
If the condition never becomes false, the loop runs forever. Sometimes intentional (game loops, servers), but usually a bug.
#include
int main() {
int i = 1;
while (i > 0) {
printf("This will go on forever...\n");
i++;
}
return 0;
}
Try it Yourself →