In this tutorial, you shall learn how to iterate over the elements of a given array using looping statements or Array.forEach() method in Kotlin, with examples.

Kotlin – Iterate over Array Elements

To iterate over Array Elements in Kotlin, we can use looping statements like For Loop, While Loop, etc., or call Array.forEach() method on this Array.

1. Iterate over Array using For loop

In the following program, we take an array of strings, and iterate over the elements of this Array. Inside For Loop, we print the element.

Main.kt

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

Output

apple
banana
cherry

For more examples to iterate over Array using For Loop, refer Kotlin Array – For Loop tutorial.

ADVERTISEMENT

2. Iterate over Array using While loop

In the following program, we take an array of strings, and iterate over the elements of this Array using While Loop. Inside While Loop, we print the element.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry")
    var i = 0
    while (i < arr.size) {
        println(arr[i])
        i++
    }
}

Output

apple
banana
cherry

3. Iterate over Array using Array.forEach() method

In the following program, we take an array of strings, and iterate over the elements of this Array using Array.forEach() method. Respective element can be accessed using it.

Main.kt

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "banana", "cherry")
    arr.forEach {
        println(it)
    }
}

Output

apple
banana
cherry

Conclusion

In this Kotlin Tutorial, we learned how to iterate over elements of an Array in different ways, in Kotlin programming language with examples.