for Loop

Looping Over a Range

Example

Kotlin has no C-style for (int i = 0; i < n; i++). You loop over a range or a collection with for (x in ...).

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

Output

Attempt 1
Attempt 2
Attempt 3
10 5 0 
[0][1][2]
// Java
for (int i = 0; i < 3; i++) { ... }
// Kotlin
for (i in 0 until 3) { ... }

Looping Over Collections and Strings

Example

Loop directly over elements. Use withIndex() or indices when you also need the position.

fun main() {
    val songs = listOf("Kesariya", "Naatu Naatu", "Jhoome Jo Pathaan")
    for (song in songs) {
        println("Playing $song")
    }
    for ((index, song) in songs.withIndex()) {
        println("${index + 1}. $song")
    }
    for (i in songs.indices) {
        println("$i -> ${songs[i].length} letters")
    }
}

Output

Playing Kesariya
Playing Naatu Naatu
Playing Jhoome Jo Pathaan
1. Kesariya
2. Naatu Naatu
3. Jhoome Jo Pathaan
0 -> 8 letters
1 -> 11 letters
2 -> 17 letters

Nested Loops

Example

A loop inside a loop: the inner loop finishes completely for each step of the outer loop.

fun main() {
    for (row in 1..3) {
        for (col in 1..row) {
            print("* ")
        }
        println()
    }
    for (i in 1..3) {
        for (j in 1..3) print("${i * j}\t")
        println()
    }
}

Output

* 
* * 
* * * 
1	2	3	
2	4	6	
3	6	9