To iterate over an array in reverse order in Kotlin, you can use the reversedArray()
method or a simple loop starting from the last index to the first index.
In this example,
numbers
with integer values.reversedArray()
method to get a reversed view of the array.fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
val reversedNumbers = numbers.reversedArray()
for (num in reversedNumbers) {
println(num)
}
}
5 4 3 2 1
In this example,
fruits
with string values.i
with the last index of the array.i >= 0
to iterate from the last index to the first index.fruits[i]
and decrement i
.fun main() {
val fruits = arrayOf("Apple", "Banana", "Cherry", "Date")
var i = fruits.size - 1
while (i >= 0) {
println(fruits[i])
i--
}
}
Date Cherry Banana Apple
In this tutorial, we learned How to Iterate Over an Array in Reverse Order in Kotlin language with well detailed examples.