Start learning free

LESSON 154 OF 677 · WHILE LOOPS & FOR LOOPS

For Loops: Printing Numbers II in Kotlin

Lesson

Let's see an example where we change the step.

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 start value is 2, so we start iterating from number 2.

  • The end value is 10, which is included because .. includes both ends. We could've written 2 until 11 step 2 and it would still be correct.

  • The step 2 part means 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