Kotlin Tutorial · Kotlin Basics · Lesson 8 of 31
Kotlin Loops and Ranges
Loop with for over ranges and collections, while and do-while, and control loops with break and continue.
for and ranges
for iterates over anything iterable. Ranges: 1..5 (inclusive), 1..<5 (excludes 5), 5 downTo 1,
step 2. withIndex() gives the index and the value.
fun main() {
for (i in 1..3) print("$i ")
println()
for (i in 0..<3) print("$i ")
println()
for (i in 10 downTo 0 step 5) print("$i ")
println()
val fruits = listOf("apple", "banana", "cherry")
for ((index, fruit) in fruits.withIndex()) println("$index: $fruit")
}
Output
1 2 3 0 1 2 10 5 0 0: apple 1: banana 2: cherry
Run this on your computer — see “Get Started” for setup.
while, break and continue
while and do { } while () work as in other languages. break and continue can target an outer loop with a
label (outer@).
fun main() {
var stock = 3
while (stock > 0) {
println("Selling one, $stock left before sale")
stock--
}
outer@ for (row in 1..3) {
for (col in 1..3) {
if (col == 2) continue
if (row == 3) break@outer
print("($row,$col) ")
}
}
println()
}
Output
Selling one, 3 left before sale Selling one, 2 left before sale Selling one, 1 left before sale (1,1) (1,3) (2,1) (2,3)
Run this on your computer — see “Get Started” for setup.
Test yourself
Which range excludes its upper bound?
1..51..<55 downTo 11 until..5
Show answer
Answer: 1..<5