Sometimes you need to repeat something until a condition changes. That's where while loops come in — keep going while the condition is true.
The while loop
A while loop checks the condition first. If it's true, the body runs, then it checks again.
fun main() {
var count = 3
while (count > 0) {
println(count)
count--
}
println("Go!")
}
The -- operator decreases count by 1 each time. Eventually count > 0 becomes false and the loop stops.
Infinite loops and breaking out
You can create an infinite loop with while (true) and use break to exit when ready.
fun main() {
var number = 1
while (true) {
if (number > 5) break
println(number)
number++
}
}
Use break sparingly — it's easy to accidentally create a loop that never ends!
The do...while loop
With do...while, the body runs at least once because the condition is checked after.
fun main() {
var x = 5
do {
println(x)
x++
} while (x < 3)
}
Even though 5 < 3 is false, the body prints 5 once before the check.