Kotlin – Iterate over an Array using For loop

Iterate over an Array using For loop in Kotlin

To iterate over an Array in Kotlin, you can use For loop statement. During each iteration, an element from the Array is accessible inside the For loop body. During first iteration, we have access to the first element in the Array, during second iteration ,we have access to the second element in the Array, and so on.

Examples

Iterate over Array of Fruit names using For loop

In the following program, we take an array of strings fruitNames, iterate over the Array using a For loop, and inside the For loop, we print the element.

Kotlin Program

fun main(args: Array<String>) {
    val fruitNames = arrayOf("apple", "banana", "cherry")
    for (name in fruitNames) {
        println(name)
    }
}

Output

apple
banana
cherry