Kotlin – Iterate over an Array using While loop

Iterate over an Array using For loop in Kotlin

To iterate over an Array in Kotlin, you can use While loop statement. We start an index at 0, and at the end of each iteration we increment the index by one. During each iteration we can access the element at the index using arrayname[index] notation.

Examples

Iterate over Array of Fruit names using While loop

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

Kotlin Program

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

Output

apple
banana
cherry