Kotlin While Loop
Loops repeat a block of code. A while loop keeps going as long as its condition is true. It's the right tool when you don't know in advance how many repetitions you need.
while
fun main() {
var countdown = 5
while (countdown > 0) {
println("T-minus $countdown")
countdown--
}
println("Liftoff!")
}T-minus 5
T-minus 4
T-minus 3
T-minus 2
T-minus 1
Liftoff!
The condition is checked before each repetition. If it is false at the start, the body never runs at all.
Note: Something in the body must eventually make the condition false. If
countdown--were missing, the loop would run forever (an infinite loop).
Loops without a known count
A classic while use case: repeat until some goal is reached. How many years until savings double at 7% interest?
fun main() {
var savings = 1000.0
var years = 0
while (savings < 2000.0) {
savings *= 1.07
years++
}
println("Doubled after $years years")
}Doubled after 11 years
do..while
A do..while loop checks the condition after the body, so the body always runs at least once. That's natural for "do something, then decide whether to repeat" — like showing a menu.
fun main() {
var attempt = 0
do {
attempt++
println("Attempt $attempt")
} while (attempt < 3)
var n = 100
do {
println("Runs once even though n >= 10")
} while (n < 10)
}Attempt 1
Attempt 2
Attempt 3
Runs once even though n >= 10
| Loop | Condition checked | Minimum runs |
|---|---|---|
while (c) { … } |
before each run | 0 |
do { … } while (c) |
after each run | 1 |
A nice detail: variables declared inside a do body are visible in its while condition.
Digits of a number
while is perfect for processing a number digit by digit:
fun main() {
var n = 90417
var sum = 0
var digits = 0
while (n > 0) {
sum += n % 10 // last digit
n /= 10 // remove last digit
digits++
}
println("Digits: $digits, digit sum: $sum")
}Digits: 5, digit sum: 21
The Collatz sequence
Here's a famous puzzle: start with any positive number; if it's even, halve it, otherwise multiply by 3 and add 1. Repeat until you reach 1. Nobody has proven it always ends — but it does for every number ever tried!
fun main() {
var n = 6
val steps = mutableListOf(n)
while (n != 1) {
n = if (n % 2 == 0) n / 2 else 3 * n + 1
steps.add(n)
}
println(steps.joinToString(" -> "))
}6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Tip: When you do know how many times to loop — "for each item", "from 1 to 10" — a
forloop is usually clearer. It's covered in an upcoming chapter.
Test yourself
How many times does the body of while (false) { ... } run?
- 0
- 1
- Forever
- Compile error
Which loop always executes its body at least once?
- while
- for
- do..while
- repeat(0)
What is the danger of forgetting to update the loop variable in a while loop?
- A compile error
- An infinite loop
- The loop runs once
- Nothing