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
while (condition) {
// Code to execute
}
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:
int contador = 1;
print('\nCiclo While Incremento');
while (contador <= 5) {
print('Contador: $contador');
contador++;
}
// Output: Contador: 1
// Contador: 2
// Contador: 3
// Contador: 4
// Contador: 5
Decrementing While Loop
You can also decrement the counter:
print('\nCiclo While Decremento');
int contador = 5;
while (contador >= 1) {
print('Contador: $contador');
contador--;
}
// Output: Contador: 5
// Contador: 4
// Contador: 3
// Contador: 2
// Contador: 1
Complete Example
void main() {
int contador = 1;
print('\nCiclo While Incremento');
while (contador <= 5) {
print('Contador: $contador');
contador++;
}
// Decrement
print('\nCiclo While Decremento');
contador = 5;
while (contador >= 1) {
print('Contador: $contador');
contador--;
}
}
When to Use While Loops
Unknown iteration count
Use while loops when the number of iterations depends on runtime conditions rather than a fixed count.
Condition-based execution
While loops are ideal when you need to continue until a specific condition is met.
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
int i = 0;
while (i < n) {
// Code
i++;
}
Counting down
int i = n;
while (i > 0) {
// Code
i--;
}
Condition-based
while (someCondition) {
// Code that may change someCondition
}
Loop Control
Use break to exit the loop early and continue to skip the current iteration:int contador = 0;
while (contador < 10) {
contador++;
if (contador == 5) {
continue; // Skip 5
}
if (contador > 7) {
break; // Exit at 8
}
print(contador);
}
Infinite Loops
Be careful to avoid infinite loops! Always ensure the condition will eventually become false:// DANGER: Infinite loop!
int x = 1;
while (x > 0) {
print(x);
x++; // x will never be <= 0
}
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
Practical Example
Here’s a practical example of reading values until a condition is met:
void main() {
int sum = 0;
int count = 1;
// Sum numbers from 1 to 10
while (count <= 10) {
sum += count;
count++;
}
print('Sum of numbers 1-10: $sum');
// Output: Sum of numbers 1-10: 55
}