Skip to the workspace
Pebellslearn by building
Conditional Expressions and Loops  ›  Lesson

while and do-while

while 12 minA while loop repeats as long as its condition is true and may run zero times, while a do-while loop runs its body first and checks afterwards, so it always runs at least once.

kotlin / while and do-while

Explore each scene at your own pace.

01 · The rule

The rule

while and do-while

A while loop repeats as long as its condition is true and may run zero times, while a do-while loop runs its body first and checks afterwards, so it always runs at least once.

Compare checking before the first iteration with checking after it.

A for loop is perfect when you know what to walk through. But "keep brewing while there are beans" has no list: you only know when to stop. That is the job of while.

The rule

while checks, then acts; do-while acts, then checks.

var beans = 50
var cups = 0
while (beans >= 18) {
    beans -= 18
    cups++
}
println("$cups cups, $beans g left")   // 2 cups, 14 g left

The condition is tested before each round. If it is false at the start, the body runs zero times.

do-while flips the order: the body runs first, then the condition decides whether to go again. So the body always runs at least once:

do {
    val size = readln()
    println("You chose $size")
} while (size !in listOf("S", "M", "L"))

This is the natural shape for "ask, and ask again if the answer was bad". Kotlin has a neat detail here: a variable declared inside the do body, like size, is visible in the while condition.

Every while loop needs something inside it that moves toward stopping, here beans -= 18. Forget it and the condition never changes, giving an infinite loop.

cups++ adds 1 to a var; cups-- subtracts 1. Both work only on variables, not on vals.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.