Skip to content

kotlin for with step

  • by
kotlin for loop with step

1. Overview

In this article, we will learn the Kotlin for with step with examples.

2. Kotlin for loop with step

The step function helps to skip or jump the iterations while iterating the collections.

The step function determines the increment between each number in the iteration sequence of the for loop. It generates each next number in the iteration by adding the step value to the preceding number.

If you don’t specify any step value, then the default value is 1.

For example, the below for loop doesn’t have any explicit step value so the default step value is 1. It executes every sequence by iterating through numbers from 1 to 8. So it prints all 1 to 8 numbers. This helps to iterate over odd or even numbers.

fun main() {
    
    for (i in 1..8) print(i) 
}

The below for loop has a step value of 2 and iterates in increments of value 2. So prints 1357.

fun main() {
    
    for (i in 1..8 step 2) print(i) 
}

It is not necessarily 2. You can have any step value.

fun main() {
    
    for (i in 1..8 step 3) print(i) 
}

3. Kotlin for loop step should be positive.

You must not specify the step value as 0 or negative value in the for loop. If you do so, it will cause the following error.

Exception in thread “main” java.lang.IllegalArgumentException: Step must be positive, was: 0.

The below code throws the error as the step is 0.

fun main() {
    
    for (i in 1..8 step 0) print(i)
    println()
}

4. step with downTo in the for loop

You can use step along with downTo function in your for loop. The downTo iterates the number in the reverse order.

Therefore, the skip function decrements the number by the step value.

The below code iterates from 8 to 1 in reverse order and so step decrements by 2. Thus, it prints 8642.

fun main() {
    
   for (i in 8 downTo 1 step 2) print(i) 
}

5. Conclusion

In this article, we have seen the Kotlin for loop with the step function along with examples. See our other articles related to Kotlin loop until and kotlin foreach with index example if you are interested.

Leave a Reply

Your email address will not be published. Required fields are marked *