The while loop syntax and execution flow
What you'll learn: How to use the while loop to repeat a block of code as long as a specific condition remains true.
The "Keep Going" Logic
In programming, you often need to repeat an action without knowing exactly how many times it will take. Think of a while loop like a security guard at a gate. Before letting you pass, the guard checks your ID. As long as your ID is valid, you can enter the building. If you come back tomorrow and your ID is expired, the guard stops you immediately.
The while loop follows this exact "check-then-act" pattern. It evaluates a condition; if the condition is true, the code inside the loop runs. Once the code finishes, the computer jumps back to the top and checks the condition again.
Basic Syntax
The structure of a while loop is minimalist and looks like this:
#include <stdio.h>
int main() {
int cookiesInJar = 3;
// The loop checks the condition inside the parentheses
while (cookiesInJar > 0) {
printf("Eating a cookie... yum!\n");
// We decrease the count, otherwise the loop runs forever!
cookiesInJar = cookiesInJar - 1;
}
printf("The jar is empty.");
return 0;
}
How the Execution Flows
- The Test: The computer looks at the condition inside
while(...). If it is true (non-zero), it enters the curly braces. If it is false (zero) right at the start, the loop is skipped entirely. - The Body: The code inside the
{ }executes line by line. - The Re-check: When the computer reaches the closing brace
}, it doesn't move to the next line of the program. Instead, it "loops" back to the top and re-evaluates the condition. - The Exit: This cycle repeats until the condition finally becomes false. At that point, the computer jumps down to the code immediately following the closing brace.
Crucially, you must ensure that something inside the loop eventually changes the condition (like eating a cookie). If the condition stays true forever, you create an "infinite loop," and your program will never stop!
Key takeaway
A while loop repeatedly executes a block of code as long as its condition evaluates to true, checking the condition before every single iteration.