The while loop
- Dart course
- Beginner
- Lesson 43/116
- 4 min
Learn loops that run while a condition holds with while.
The while loop
A while loop repeats the block as long as a condition is true. The form is while (condition) { ... }. The condition is checked before each iteration; when false the loop ends.
For example var i = 5; while (i > 0) { print(i); i--; } prints 5, 4, 3, 2, 1. Note: without i-- the loop is infinite because i stays 5 and the condition stays true.
Condition and update
In while the condition is written in parentheses and checked before each iteration. If true the body runs; if false the loop ends. The body must include a change (increase or decrease) that progresses the condition; otherwise the loop is infinite.
An infinite loop stops the program from continuing. The form while (true) always produces true; without a break inside it becomes an infinite loop. Practical tip: when writing while make sure the condition will become false at some point.
Practice Count down from 5 to 1
Start with var i = 5;. Build a while (i > 0) loop; in the body print with print(i); and decrease with i--;. The output must be 5 lines: 5, 4, 3, 2, 1 (one number per line).
Starter code
// Count down from 5 to 1 with while and print eachSample solution
var i = 5;
while (i > 0) {
print(i);
i--;
}Expected output
5 4 3 2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the while condition
var i = 5;
while (____) {
print(i);
i--;
}
var i = 5;
while (i > 0) {
print(i);
i--;
}
Explanation: The condition i > 0 is true as long as i is greater than 0.
2 Which one causes an infinite loop?
// while examples- while (i < 10) { i++; }
- while (true) { print(i); } Correct answer
- while (i > 10) { i--; }
- while (i < 10) { break; }
Explanation: The condition while (true) is always true, so the loop is infinite.
3 Match each part to its job
| Term | Meaning |
|---|---|
while (cond) |
Condition check |
{ ... } |
Body |
i-- |
Decrease |
i > 0 |
Condition example |