Kotlin · Module 2 · Lesson 21 min read

Loops & Ranges

Ranges

RangeValues
1..51, 2, 3, 4, 5 (inclusive)
1 until 5 or 1..<51, 2, 3, 4
10 downTo 110, 9, …, 1
1..10 step 21, 3, 5, 7, 9
'a'..'e'characters
Check membership: if (age in 13..19) println("teen").

for loops

kotlin
for (i in 1..3) println(i)
for (name in names) println(name)
for ((index, name) in names.withIndex()) println("$index: $name")
for ((key, value) in map) println("$key = $value")

while and do-while

kotlin
while (lives > 0) { … }
do { input = readLine() } while (input.isNullOrBlank())

break, continue and labels

kotlin
outer@ for (i in 1..3) {
    for (j in 1..3) {
        if (j == 2) continue@outer
        println("$i,$j")
    }
}

repeat

repeat(3) { println("Hello") } when you just need to do something N times.

Often you don't need a loop

Collection functions like forEach, map, filter and sum (Unit 4) are usually clearer than manual loops.

Example

kotlin
fun main() {
    for (i in 1..5) print("$i ")
    println()
    for (i in 1 until 5) print("$i ")
    println()
    for (i in 10 downTo 0 step 3) print("$i ")
    println()

    val fruits = listOf("Apple", "Mango", "Kiwi")
    for ((i, f) in fruits.withIndex()) println("$i: $f")

    val stock = mapOf("pens" to 12, "books" to 3)
    for ((item, qty) in stock) println("$item → $qty")

    var lives = 3
    while (lives > 0) { println("Lives left: $lives"); lives-- }

    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (j == 2) continue@outer
            println("pair $i,$j")
        }
    }
    repeat(2) { println("Kotlin rocks #${it + 1}") }
    println("Is 15 a teen age? ${15 in 13..19}")
}