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 block at least once, then checks the condition. If the condition is true, the loop continues.

var n = 0
do {
    println(n)
    n = n + 1
} while (n < 3)

This prints 0, 1, 2. The block runs first, then n < 3 is checked. Unlike while, the condition is at the end, so the block always runs at least once.

It is useful when you need at least one pass, like reading input.

Practice Count 0 to 2 with do-while

Write a fun main(). Assign 0 to var n. Use do { println(n); n = n + 1 } while (n < 3) to print 0, 1, 2.

Starter code

Main.kt
fun main() {
    // Count with do-while
}

Sample solution

Main.kt
fun main() {
    var n = 0
    do {
        println(n)
        n = n + 1
    } while (n < 3)
}

Expected output

0
1
2

When to use do-while?

do-while is used when the block must run at least once, even if the condition is false the first time.

var n = 10
do {
    println(n)
    n = n - 1
} while (n > 10)

Here the condition n > 10 is false from the start; but the block still runs once and prints 10. A while loop would not run at all.

This matters especially for first-pass steps that must always execute.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the while keyword

Question
do {
    println(n)
    n = n + 1
} ____ (n < 3)
Answer
do {
    println(n)
    n = n + 1
} while (n < 3)

Explanation: } while (n < 3) completes the do-while.

2 Match the do-while behavior

Term Meaning
do { ... } while Runs first then checks
while (...) Checks first then runs
condition true Continues
condition false (first time) do-while still runs

3 How does do-while differ from while?

  • It runs faster
  • It needs less code
  • It runs at least once even if the condition is false Correct answer
  • It only works with numbers

Explanation: do-while checks the condition at the end; the block always runs at least once.

All lessons in Beginner