Updating the loop variable to avoid infinite loops
What you'll learn: You will learn how to modify a variable within your while loop to ensure the condition eventually becomes false and the program continues.
The Engine Needs a Steering Wheel
Imagine a while loop as a car driving down a highway. The condition is the signpost telling the car when to exit. If you never change the car's position or the distance traveled, you will drive forever, effectively trapped in a "loop."
In C, a while loop checks a condition. If it is true, it runs the code inside the curly braces. After it finishes that code, it jumps back to the top and checks the condition again. If the variables inside that condition never change, the condition stays true forever. This is called an infinite loop, and it will cause your program to freeze or crash because it is stuck doing the same task over and over.
The Increment Step
To prevent this, you must include an update statement inside the loop body. This is a line of code that changes the value of the variable being tested in the loop's condition. Usually, we do this at the very end of the loop body.
Common ways to update a variable include:
- Incrementing:
count = count + 1;(orcount++;) - Decrementing:
countdown = countdown - 1; - Adjusting by a specific amount:
balance -= 10;
Seeing it in Action
In the example below, notice what happens to the variable bottles. Without the line that subtracts one, the program would print the same line until you manually forced the program to stop.
#include <stdio.h>
int main() {
int bottles = 3;
while (bottles > 0) {
printf("There are %d bottles on the wall.\n", bottles);
// THE UPDATE: Without this, the loop never ends!
bottles = bottles - 1;
}
printf("All gone!\n");
return 0;
}
By changing bottles inside the loop, we are actively working toward the moment when bottles > 0 becomes false. Once bottles hits 0, the loop "breaks," the program "exits" the curly braces, and moves on to the final print statement. Always ensure your loop body contains a "path to exit" by updating your control variable.
Key takeaway
Every while loop needs an update statement that modifies the loop variable, ensuring the condition eventually turns false.