The do-while loop
- Dart course
- Beginner
- Lesson 44/116
- 4 min
Learn loops that run at least once with do-while.
The do-while loop
The do-while loop runs the body first, then checks the condition. The form is do { ... } while (condition);. Even if the condition is false the body runs at least once; this is the key difference from while.
For example var i = 1; do { print(i); i++; } while (i <= 3); prints 1, 2, 3. First print(i) and i++ run, then i <= 3 is checked. If true the loop repeats.
At least once
The key feature of do-while is that the body runs at least once. Because the condition is checked after the body, even if the condition is false from the start the body runs once. This behavior is useful especially when reading user input.
For example, to show a menu at least once and repeat until the user picks 'exit', do-while fits well. The same behavior with while needs an extra flag variable; do-while is cleaner. Practical tip: pick do-when when 'at least once' is needed.
Practice Count 1 to 5 with do-while
Start with var i = 1;. Build a do { ... } while (i <= 5); loop; in the body print with print(i); and increase with i++;. The output must be 5 lines: 1, 2, 3, 4, 5 (one number per line).
Starter code
// Count 1 to 5 with do-while and print eachSample solution
var i = 1;
do {
print(i);
i++;
} while (i <= 5);Expected output
1 2 3 4 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each part to its job
| Term | Meaning |
|---|---|
do { |
Body start |
} while (cond); |
Condition and end |
i++ |
Increase |
print(i) |
2 Write the do-while condition
var i = 1;
do {
print(i);
i++;
} while (____);
var i = 1;
do {
print(i);
i++;
} while (i <= 3);
Explanation: The condition i <= 3 is true while i is 3 or below.
3 How many times does do { print(i); } while (false); run?
do {
print("hello");
} while (false);- 0 times
- 2 times
- 1 time Correct answer
- Infinitely
Explanation: The do-while body runs before the condition; even false it runs once.