In this tutorial, you shall learn how to iterate over the elements of a given array using While loop in Kotlin, with examples.

Kotlin Array – While Loop

To iterate over elements of an Array in Kotlin, we can use While Loop. Inside the While Loop body, we can access respective element of the iteration.

Refer Kotlin While Loop tutorial.

Syntax

The syntax to iterate over elements of an Array arr using While Loop is

</>
Copy
var i = 0
while (i < arr.size) {
    // arr[i]
    // i++
}

where we can access the element inside for loop body.

Examples

1. Iterate over string 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

</>
Copy
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

Conclusion

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