Start learning free

LESSON 121 OF 348 · WHILE LOOPS & FOR LOOPS

Changing the Step in a Kotlin For Loop

Lesson Read the full explanation

Let's see an example where we change the iteration statement.

We can print all even numbers from 2 through 10:

for (i in 2..10 step 2) {
	println(i)
}

The output of this code is:

2
4
6
8
10

Let's break down this code:

  • The initialization statement is int i = 2, so we start iterating from number 2.

  • The condition statement is i <= 10 so we end at number 10. We could've written i < 11 and it would still be correct.

  • The iteration statement is i += 2, so we increase our number by 2 every time.


Assignment

Let's print all odd numbers from 7 through 23 using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    KOTLIN · WHILE LOOPS & FOR LOOPS

    Printing Numbers 4 in Kotlin, explained

    Skipping values with step

    By default a range moves up by 1. To move by a different amount, add step after the range:

    for (i in 2..10 step 2) {
        println(i)
    }
    

    This prints the even numbers from 2 through 10:

    2
    4
    6
    8
    10
    

    Read it from left to right: start at 2, go up to 10, and take steps of 2. The loop visits 2, then 4, 6, 8 and 10, and the next value, 12, is past the end, so it stops.

    How the three parts map to the range

    • Start: the left end of the range, here 2.
    • End: the right end, here 10. Because .. includes its end, 10 is printed since the steps happen to land on it.
    • Step: the number after step, here 2. It is the amount added after every pass.

    The end does not have to be hit exactly

    The range gives an upper limit, not a promised last value. A loop stops at the last value that does not go past the end. With a step that does not land on the end, the end is simply never printed:

    for (i in 1..10 step 4) {
        println(i)
    }
    

    This prints 1, 5 and 9. The next value, 13, is beyond 10. This is why a range is safer than an exact test like "stop when the counter equals 10", which could be jumped over.

    Rules for step

    • The step must be positive. A step of 0 or a negative number throws an IllegalArgumentException when the loop starts, with the message Step must be positive, was: -2. (or 0). To count downward, use downTo with a positive step, as the next lessons show.
    • step belongs to a range. It follows .., until or downTo. 0 until 10 step 5 visits 0 and 5.
    • Parentheses are optional. 2..10 step 2 is a call written in infix form, the same as (2..10).step(2). Using it without parentheses is the usual style.

    The exercise: odd numbers from 7 through 23

    The task is to print all odd numbers from 7 through 23: 7, 9, 11, and so on up to 23.

    1. Choose the start and end. The first odd number is 7 and the last is 23, so the range is 7..23.
    2. Choose the step. Consecutive odd numbers differ by 2. Starting at an odd number and adding 2 each time never leaves the odd numbers, so add step 2.
    3. Print each value. The body is println(i).

    The trick is that the start decides the parity. If the loop began at 8 with the same step, it would print even numbers instead. You do not need an if to test oddness.

    The solution in Kotlin

    for (i in 7..23 step 2) {
        println(i)
    }
    

    It prints 7, 9, 11, 13, 15, 17, 19, 21 and 23, one per line. That is nine lines.

    Details worth knowing

    • Counting the passes. The number of values is the distance divided by the step, rounded down, plus one: (23 - 7) / 2 + 1 is 9.
    • Same result with until. 7 until 24 step 2 visits the same nine values. Both forms are correct.
    • Filtering is an alternative, not a better one. You could loop over every number and print only those with i % 2 == 1. It runs twice as many passes. step says the intent directly.

    Common mistakes

    • Wrong first value. Starting at 6 or 8 prints even numbers, as the parity follows the start.
    • Using step without a range. for (i in step 2) does not compile.
    • Using a step of 1 and forgetting to filter. It prints every number from 7 to 23.
    • Expecting the end to be printed. With a step that skips over it, as in 1..10 step 4, the end never appears.

    Key takeaways

    • a..b step k visits a, a + k, a + 2k and so on, while the value is at most b.
    • The step must be positive.
    • The start value decides whether you get even or odd numbers when the step is 2.
    • For odd numbers from 7 through 23: for (i in 7..23 step 2) { println(i) }.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free