Kotlin – Iterate over a Range in Reverse Order

Iterate over a Range in Reversed order in Kotlin

To iterate over a range in reversed order in Kotlin, call reversed() function on the range object and iterate over this reversed range object using a For loop.

The syntax to iterate over a range [x, y] in reversed order is

val myRange = x..y
for (element in myRange.reversed()) {
  //your code
}

Examples

In the following examples, you will learn how to iterate over a range of numbers in reversed order using For loop.

1. Iterate over the range 4..9 in reversed order

In the following program, we take an integer range 4..9, and iterate over the elements of this range in reversed order.

Kotlin Program

fun main() {
    val myRange = 4..9
    for (i in myRange.reversed()) {
        println(i)
    }
}

Output

9
8
7
6
5
4

2. Iterate over the range 10..90 with a step of 10 in reversed order

In the following program, we take a range 10..90 with a step of 10 in myRange object, and iterate over this range in reversed order.

Kotlin Program

fun main() {
    val myRange = 10..90 step 10
    for (i in myRange.reversed()) {
        println(i)
    }
}

Output

90
80
70
60
50
40
30
20
10