Kotlin – Iterate over Range of Numbers

Iterate over a Range of Numbers in Kotlin

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

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

for (element in x..y) {
  //your code
}

Examples

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

Iterate over the range 4..9

In the following program, we take an integer range 4..9, and print each of the element to output in a For loop.

Kotlin Program

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

Output

4
5
6
7
8
9

Iterate over the range -3..3

In the following program, we take an integer range from -3 to 3, and print each of the element to output in a For loop.

Kotlin Program

fun main() {
    for (i in -3..3) {
        println(i)
    }
}

Output

-3
-2
-1
0
1
2
3