Loops in Kotlin
From the Kotlin cheat sheet · Control Flow · verified Jul 2026
Loops
for, while, and loop control
kotlin
// For loops
for (i in 1..5) {
println(i) // 1, 2, 3, 4, 5
}
for (i in 1 until 5) {
println(i) // 1, 2, 3, 4
}
for (i in 5 downTo 1) {
println(i) // 5, 4, 3, 2, 1
}
for (i in 1..10 step 2) {
println(i) // 1, 3, 5, 7, 9
}
// Iterating collections
val list = listOf("a", "b", "c")
for (item in list) {
println(item)
}
for ((index, value) in list.withIndex()) {
println("$index: $value")
}
// While loops
var x = 5
while (x > 0) {
println(x--)
}
// Do-while
do {
val y = readLine()
} while (y != "exit")💡 Ranges (1..5) and progressions (step, downTo) control iteration
⚡ withIndex() provides index-value pairs for iteration
📌 Labels allow breaking/continuing outer loops
🟢 forEach is inline, so return exits the enclosing function