Overview
While loops execute a block of code repeatedly as long as a condition remains true. Unlike for loops, while loops are ideal when you don’t know in advance how many iterations are needed.Basic Syntax
The condition is checked before each iteration. If the condition is false initially, the loop body never executes.
Incrementing While Loop
A basic while loop that increments a counter:Decrementing While Loop
You can also decrement the counter:Complete Example
When to Use While Loops
1
Unknown iteration count
Use while loops when the number of iterations depends on runtime conditions rather than a fixed count.
2
Condition-based execution
While loops are ideal when you need to continue until a specific condition is met.
3
Reading input
Useful for reading user input or processing data until a sentinel value is encountered.
While vs For Loops
Use For Loop When:
- You know the exact number of iterations
- You’re iterating over a range of numbers
- You’re iterating over a collection
Use While Loop When:
- The number of iterations is unknown
- The loop depends on external conditions
- You’re waiting for a specific state to occur
Common Patterns
Counting up
Counting down
Condition-based
Loop Control
Infinite Loops
Best Practices
- Always initialize the loop variable before the loop
- Ensure the condition will eventually become false
- Update the loop variable inside the loop body
- Use meaningful variable names
- Consider using for loops when the iteration count is known
- Add safety mechanisms (like maximum iteration counts) for potentially infinite loops