Kotlin Range with Step Value

Range with Step Value in Kotlin

To define a range with a specific step value in Kotlin, use step function with the range object.

For example, if would like to define an integer range [4, 25] with a step value of 3, use the following syntax.

4..25 step 3

Also, if would like to define an character range ['a', 'z'] with a step value of 5, use the following syntax.

'a'..'z' step 3

Examples

In the following examples, you will learn how to define a range with a step value.

1. Range of 4..25 with a step value of 3

In the following program, we take define a range 4..25 with a step value of 3, and print the elements of this range.

Kotlin Program

fun main() {
    val myRange = 4..25 step 3
    for (i in myRange) {
        println(i)
    }
}

Output

4
7
10
13
16
19
22
25

2. Range of 20..100 with a step value of 10

In the following program, we take define a range 20..100 with a step value of 10, and print the elements of this range.

Kotlin Program

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

Output

20
30
40
50
60
70
80
90
100

3. Character Range with step

In the following program, we take define a character range 'a'..'z' with a step value of 5, and print the elements of this range.

Kotlin Program

fun main() {
    val myRange = 'a'..'z' step 5
    for (ch in myRange) {
        println(ch)
    }
}

Output

a
f
k
p
u
z