Writing Effective while Loop Conditions
You'll learn how to write boolean expressions that control while loops safely and effectively, including how to avoid infinite loops.
What Makes a Good Loop Condition?
A while loop continues executing as long as its condition evaluates to true. The condition is a boolean expression—something that produces either true or false. Writing effective conditions means ensuring your loop will:
- Eventually become false (preventing infinite loops)
- Clearly express the loop's purpose
- Be efficient and safe (using short-circuit evaluation when appropriate)
Common Patterns for Loop Conditions
Counting patterns:
int count = 0;
while (count < 10) {
count++;
}
Sentinel value patterns:
int value = 5;
while (value != -1) {
// Process value, then update it
value--; // This will eventually reach -1
}
Compound conditions:
int x = 0;
int y = 10;
while (x < 5 && y > 0) {
x++;
y--;
}
Avoiding Infinite Loops
An infinite loop runs forever because its condition never becomes false. This typically happens when you forget to update the variables in the condition:
// DANGER: Infinite loop!
int count = 0;
while (count < 10) {
// Missing: count++ or count--;
}
Always ensure that something inside the loop body changes the state that affects the condition.
Key Considerations
- Use relational operators (
<,>,<=,>=,==,!=) appropriately - Combine conditions with logical operators (
&&,||) when needed - Leverage short-circuit evaluation for efficiency and safety
- Make sure variables in the condition are modified inside the loop
Key Takeaway: An effective while loop condition must eventually evaluate to false by tracking variables that change inside the loop body—otherwise, you risk creating an infinite loop.