For in Kotlin

Kotlin provides several ways to create loops. Here are some basic types of loops in Kotlin.

fun main() {
    // The most basic type, with a single condition.
    var i = 1
    while (i <= 3) {
        println(i)
        i = i + 1
    }

    // A classic initial/condition/after for loop.
    for (j in 0 until 3) {
        println(j)
    }

    // Another way of accomplishing the basic "do this
    // N times" iteration is using a range.
    for (i in 0..2) {
        println("range $i")
    }

    // A loop without a condition will run repeatedly
    // until you break out of the loop or return from
    // the enclosing function.
    while (true) {
        println("loop")
        break
    }

    // You can also continue to the next iteration of
    // the loop.
    for (n in 0..5) {
        if (n % 2 == 0) {
            continue
        }
        println(n)
    }
}

When you run this program, you’ll see:

1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Kotlin, the for loop is primarily used for iterating over ranges, arrays, and other collections. The while loop is used for condition-based looping. The do-while loop (not shown in this example) is another option when you need the loop body to execute at least once.

We’ll see some other loop forms later when we look at ranges, collections, and other data structures.