Using while for indeterminate iterations
What you'll learn: How to use a while loop to repeat code when you don't know exactly how many times the loop needs to run in advance.
The "Are we there yet?" Loop
In programming, we often face situations where we can't predict the future. If you are reading a file, you don't always know how many lines it has. If you are waiting for a user to type "quit," you don't know if they will do it in two seconds or two hours.
Unlike a for loop, which is usually built for counting a specific number of steps, the while loop is designed for indeterminate iterations. Think of it like a car journey: a for loop is saying "drive exactly 50 miles," whereas a while loop is saying "keep driving as long as the gas tank isn't empty." You don't know the exact mileage, but you know the condition that keeps you moving.
How it works
The while loop checks a condition. If the condition is true, the code inside the curly braces runs. Once the code finishes, it jumps back to the top and checks the condition again. This repeats until the condition finally becomes false.
#include <stdio.h>
int main() {
int cookiesInJar = 5;
// We don't know how many loops it takes to reach 0
// if the logic inside were more complex!
while (cookiesInJar > 0) {
printf("Eating a cookie... %d left.\n", cookiesInJar);
// Change the state so the loop eventually ends
cookiesInJar--;
}
printf("The jar is empty!\n");
return 0;
}
Guarding the gate
The most important thing to remember is that the condition is checked before the loop runs. If the condition is false right at the start (for example, if cookiesInJar was already 0), the code inside the loop will never execute at all.
When using while for indeterminate tasks, always ensure that something inside your loop eventually changes the condition. If cookiesInJar never decreased, you would be stuck in an "infinite loop," eating cookies forever in a digital limbo!
Key takeaway
Use a while loop when the number of repetitions depends on a condition being met, rather than a fixed count.