Search code examples
for-loopkotlinreverse

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


now i'm trying to make reversed for a loop.The simple way of reverse for is for(i in start downTo end)

but,what if I use array as a start/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])
    }