In this tutorial, you shall learn how to iterate over the elements of a given array using For loop in Kotlin, with examples.
Kotlin Array – For Loop
To iterate over elements of an Array in Kotlin, we can use For Loop. Inside the For Loop body, we can access respective element of the iteration.
Refer Kotlin For Loop tutorial.
Syntax
The syntax to iterate over elements of an Array arr
using For Loop is
for (element in arr) {
//code
}
The syntax to iterate over indices of an Array arr
using For Loop is
for (index in arr.indices) {
//code
}
The syntax to iterate over indices and elements of an Array arr
using For Loop is
for ((index, element) in arr.withIndex()) {
//code
}
Examples
1. Iterate over elements of an array
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
2. Iterate over the indices of an array
In the following program, we take an array of strings, and iterate over the indices of this Array. Inside For Loop, we print the respective element.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry")
for (i in arr.indices) {
println(arr[i])
}
}
Output
apple
banana
cherry
3. Access index of the element in the For loop
In the following program, we take an array of strings, and iterate over the indices and elements of this Array. Inside For Loop, we print the index and respective element.
Main.kt
fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry")
for ((index, element) in arr.withIndex()) {
println("[$index] - $element")
}
}
Output
[0] - apple
[1] - banana
[2] - cherry
Conclusion
In this Kotlin Tutorial, we learned how to iterate over elements of an Array using For Loop, in Kotlin programming language with examples.