In this tutorial, you shall learn how to iterate over a range in Kotlin, using For loop statement, with example programs.

Kotlin – For i in range

To iterate over a range of numbers in Kotlin, we can use use For loop.

The syntax to iterate over the range [a, b] using For loop is

for i in a..b {
  //statement(s)
}
  • for, in: are keywords.
  • i: is the value of number in current iteration.
  • a..b: is the range.

To specify a step value in the range, we can use the following syntax.

for i in a..b step s {
  //statement(s)
}

Examples (2)

ADVERTISEMENT

1. For i in 4..9

In the following program, we iterate For loop in the range [4,9],

Main.kt

fun main() {
    for (i in 4..9) {
        println(i)
    }
}

Output

4
5
6
7
8
9

2. For i in 4..20 in steps of 3

In the following program, we iterate For loop in the range [4,20] in steps of 3,

Main.kt

fun main() {
    for (i in 4..20 step 3) {
        println(i)
    }
}

Output

4
7
10
13
16
19

Conclusion

In this Kotlin Tutorial, we learned how to iterate over a range of numbers using For loop.