Kotlin While Loop
The while loop repeats a block of code as long as a condition remains true, and Kotlin's do-while variant guarantees the block runs at least once.
The while Loop
A while loop checks its condition before each iteration. If the condition is false the very first time, the loop body never executes at all. This makes while ideal when the number of repetitions isn't known ahead of time.
Basic while loop
fun main() {
var count = 1
while (count <= 5) {
println("Count is $count")
count++
}
}The do-while Loop
A do-while loop checks its condition after running the body, so the body always executes at least once, even if the condition is false from the start. This is useful for things like input validation, where you need to run the logic once before you can evaluate whether to repeat it.
do-while loop
fun main() {
var attempts = 0
val correctPin = 1234
var enteredPin: Int
do {
enteredPin = 1234 // simulating user input
attempts++
} while (enteredPin != correctPin && attempts < 3)
println("Unlocked after $attempts attempt(s)")
}A Notable Kotlin Scoping Rule
Because the do-while condition is checked after the body, Kotlin allows the condition to reference variables declared inside the loop body — something a plain while loop cannot do, since its condition is evaluated before the body's variables exist.
- while checks the condition first, so zero iterations are possible.
- do-while checks the condition last, guaranteeing at least one iteration.
- Both loops require the condition to eventually become false, or they run forever.
Summing until a limit
fun main() {
var sum = 0
var number = 1
while (sum < 50) {
sum += number
number++
}
println("Final sum: $sum, reached with number = ${number - 1}")
}Exercise: Kotlin While Loop
What is the key difference between a while loop and a do-while loop in Kotlin?