CodeBlanks Logo Icon CodeBlanks

The do-while loop

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

main.dart
// Count 1 to 5 with do-while and print each

Sample solution

main.dart
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) Print

2 Write the do-while condition

Question
var i = 1;
do {
  print(i);
  i++;
} while (____);
Answer
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?

main.dart
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.

All lessons in Beginner