Start learning free

LESSON 153 OF 677 · WHILE LOOPS & FOR LOOPS

For Loops: Printing Numbers in Kotlin

Lesson

We can achieve many different outcomes with for loops.

It's all about tuning the start value, end value and step of the range.

For example, we can print all numbers from 2 through 6:

for (i in 2..6) {
	println(i)
}

The output of this code is:

2
3
4
5
6

Let's break down this code:

  • The start value is 2, so we start iterating from number 2.

  • The end value is 6. The .. range includes both ends, so 6 is printed. We could've written 2 until 7 and it would still be correct.

  • The step is 1 by default, so we increase our number by 1 every time.


Assignment

Let's print all numbers from 3 through 10 using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check