The loop condition: when to stop
What you'll learn: You will understand how a while loop uses a boolean expression to decide exactly when to keep running and when to quit.
The Bouncer at the Door
Imagine you are standing at the entrance of a club. The bouncer has one rule: "You can stay inside as long as you have money in your pocket." Every time you want to buy a drink (run the code inside the loop), the bouncer checks your wallet. If you have $1 or more, you stay. The moment your wallet is empty, he kicks you out.
In C, the while loop works exactly like that bouncer. The code inside the curly braces will repeat over and over, but only while the condition inside the parentheses remains true.
The Logic of "While"
A while loop doesn't count how many times it has run; it simply checks a snapshot of reality before every iteration. If the condition is true, it enters the loop. If it is false, it skips the loop entirely and moves to the next part of your program.
#include <stdio.h>
int main() {
int coffee_cups = 3;
// The condition is: Is coffee_cups greater than 0?
while (coffee_cups > 0) {
printf("Drinking a cup... %d left.\n", coffee_cups);
// We change the reality so the condition eventually becomes false
coffee_cups = coffee_cups - 1;
}
printf("Out of coffee! Time to work.\n");
return 0;
}
When does it stop?
In the example above, the loop checks the condition coffee_cups > 0.
- First check: 3 is greater than 0 (True). Drink coffee.
- Second check: 2 is greater than 0 (True). Drink coffee.
- Third check: 1 is greater than 0 (True). Drink coffee.
- Fourth check: 0 is NOT greater than 0 (False).
The moment the condition becomes false, the loop breaks instantly. If you forget to change the variable (like subtracting 1 from the coffee), the condition will stay true forever, creating an "infinite loop" where you drink coffee until the computer crashes!
Key takeaway
A while loop repeats its code as long as its condition evaluates to true, checking that condition once before every single lap.