while, do-while, break, and continue
Prerequisites: Loops: for and for-in
A while loop repeats as long as its condition stays true — useful
when you don't know in advance how many times to loop.
while
void main() {
var balance = 100;
var months = 0;
while (balance < 200) {
balance += balance ~/ 10;
months++;
}
print('Doubled after $months months: $balance');
}
Doubled after 8 months: 212
do-while
do { } while (condition); checks after each pass, so the body always
runs at least once:
void main() {
var attempts = 0;
do {
attempts++;
print('Attempt $attempts');
} while (attempts < 3);
}
Attempt 1
Attempt 2
Attempt 3
break and continue
breakstops the loop completely.continueskips to the next pass.
void main() {
for (var n = 1; n <= 10; n++) {
if (n.isEven) continue;
if (n > 7) break;
print(n);
}
}
1
3
5
7
Common mistakes
- Forgetting to change the variable in a
whilecondition, so the loop never ends. Stop a runaway program with Ctrl + C.
Practice
Starting from 1, keep doubling a number while it's below 1,000, then print the first value that reached 1,000 or more.
Show solution
void main() {
var n = 1;
while (n < 1000) {
n *= 2;
}
print(n);
}
1024