Kotlin — While loops
A Kotlin while loop evaluates its Boolean condition before each pass. Use var for state that must change inside the loop.
A simple example
Print while the number is at most 3
- Start with n starts at 1
- Do this Print n, add 1
- Result Stop at 4
fun main() {
var n = 1
while (n <= 3) {
println(n)
n++
}
}
1 2 3
Pack whole batches from stock
Count complete batches of five items by repeatedly removing five while enough stock remains. Keep the leftover units for the next order. The batch counter and the stock change together. A positive batch size and decreasing stock guarantee termination for the nonnegative starting quantity.
The canteen has 17 apples and packs five in each bag. Check the remaining pile before filling each bag. Three full bags leave two apples for the next delivery.
Run the example
Use Kotlin 2.2 on the JVM. Run these commands from the directory containing the example.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
fun main() {
var stock = 17
var batches = 0
while (stock >= 5) {
stock -= 5
batches++
}
println("$batches batches, $stock left")
}
3 batches, 2 left
Seventeen items shrink to 12, 7, then 2. The condition is tested again at 2 and the body stops after three batches.
Try it yourself
What happens with four items? What about exactly five?
Check your answer
Four items yield zero batches and four leftovers. Five items yield one batch and no leftovers because the comparison includes equality.