while and do-while Loops
Prerequisites: for loops and ranges
A while loop repeats as long as its condition stays true — useful
when you don't know in advance how many times to loop.
Real-world analogy: "While the kettle isn't boiling, keep waiting."
while
fun main() {
var balance = 100
var months = 0
while (balance < 200) {
balance += balance / 10
months++
}
println("Doubled after $months months: $balance")
}
Doubled after 8 months: 212
The condition is checked before each pass. If it's false from the start, the body never runs.
do-while
do { } while (condition) checks after each pass, so the body
always runs at least once:
fun main() {
var attempts = 0
do {
attempts++
println("Attempt $attempts")
} while (attempts < 3)
}
Attempt 1
Attempt 2
Attempt 3
It's the natural fit for "keep asking until the input is valid".
Common mistakes
- Forgetting to change the variable in the condition, so the loop never ends. Stop a runaway program with the IDE's red stop button or Ctrl + C.
- Using
whilewith a counter to walk through a list. Aforloop is clearer and can't go out of bounds.
Practice
Starting from 1, keep doubling a number while it's below 1,000, then print the first value that reached 1,000 or more.
Show solution
fun main() {
var n = 1
while (n < 1000) {
n *= 2
}
println(n)
}
1024