Syntax
A while loop repeats as long as its condition remains true. The condition is checked before each iteration.
while (condition) {
// runs while condition is true
}
Example
void main() {
// Count 1 to 5
int i = 1;
while (i <= 5) {
print('i = $i');
i++;
}
// Sum until total exceeds 50
int total = 0;
int num = 1;
while (total <= 50) {
total += num;
num++;
}
print('Total: $total after adding $num numbers');
// Simulate user input validation
int attempts = 0;
String password = 'dart123';
String input = 'wrong';
while (input != password && attempts < 3) {
attempts++;
print('Attempt $attempts: wrong password');
if (attempts < 3) input = 'wrong'; else input = 'dart123';
}
print('Access granted: $${input == password}');
}
Output:i = 1 ... i = 5
Total: 56 after adding 11 numbers
Attempt 1: wrong password
Attempt 2: wrong password
Attempt 3: wrong password
Access granted: true
When to Use While
Use while when you do not know the number of iterations in advance — for example, reading input until the user types "quit", or processing data until a condition changes.
⚠️ Infinite Loop Warning
Always ensure the condition eventually becomes false, or use break to exit. Forgetting to update the loop variable causes an infinite loop:
// DANGER — infinite loop:
int x = 0;
while (x < 5) {
print(x);
// x is never incremented!
}
💪 Exercise
- Print all powers of 2 that are less than 1000 using a while loop.
- Use a while loop to find the first number greater than 100 that is divisible by 13.
🧠 Quiz
1. When is the condition of a while loop checked?
- A) After the loop body
- B) Before the loop body ✅
- C) In the middle
- D) Only once
Summary
The while loop checks its condition before each iteration. Use it when the number of iterations is unknown. Always update the condition variable inside the loop to avoid infinite loops.