Search code examples
for-loopkotlinreverse

How to make reversed for loop with array index as a start/end point in Kotlin?


I tried to create a reversed loop. The simplest way to reverse a for loop is: for (i in start downTo end)

But what if I want to use an array as the start or end point?


Solution

  • You can loop from the last index calculated by taking size - 1 to 0 like so:

    for (i in array.size - 1 downTo 0) {
        println(array[i])
    }
    

    Even simpler, using the lastIndex extension property:

    for (i in array.lastIndex downTo 0) {
        println(array[i])
    }
    

    Or you could take the indices range and reverse it:

    for (i in array.indices.reversed()) {
        println(array[i])
    }