Part 04 / Topic 6 of 8
while and do-while
Both repeat a body while a condition holds, but check that condition at opposite ends.
while |
do-while |
|
|---|---|---|
| Condition checked | before each run, including the first | after each run |
Body runs if the condition starts false |
never | once, always |
| Typical use | "keep going while this holds" | "do this, then check whether to repeat" |
var ticketsLeft = 3
while (ticketsLeft > 0) {
println("Selling ticket, $ticketsLeft left")
ticketsLeft--
}
println("Counter after the loop: $ticketsLeft")
var seatsLeft = 0
while (seatsLeft > 0) {
println("This line never prints")
seatsLeft--
}
println("Seats left: $seatsLeft")
Selling ticket, 3 left
Selling ticket, 2 left
Selling ticket, 1 left
Counter after the loop: 0
Seats left: 0
do-while runs its body first, then checks — so even a condition that's already false on entry
still gets one run:
var attempt = 0
do {
attempt++
println("Connection attempt $attempt")
} while (attempt < 3)
var retries = 5
do {
println("do-while still runs once even though retries ($retries) is not < 3")
} while (retries < 3)
Connection attempt 1
Connection attempt 2
Connection attempt 3
do-while still runs once even though retries (5) is not < 3
🔍 Going deeper: a variable declared inside a
dobody stays visible in its ownwhilecondition — the one case where Kotlin lets the condition see something declared in the body:var n = 0 do { n++ val doubled = n * 2 println("n=$n doubled=$doubled") } while (doubled < 6)n=1 doubled=2 n=2 doubled=4 n=3 doubled=6A plain
while's condition is checked before the body even starts, so it has no equivalent — any variable the condition needs must already exist above the loop.
Full program: examples/06_while_and_do_while.kt.
Done here? The practice set for Part 4 — including the solutions — is on the part page.