Start learning free

LESSON 155 OF 677 · WHILE LOOPS & FOR LOOPS

Looping In Reverse in Kotlin

Lesson

A for loop can also count backwards, as long as we define the right conditions. For example:

for (i in 7 downTo 3) {
	println(i)
}

The output of this code is:

7
6
5
4
3

Let's break down this code:

  • The loop variable i takes the values of the progression 7 downTo 3, so we start iterating from number 7.

  • downTo includes its end value, so we'll end at number 3. We could've written 7 downTo 3 as 7 downTo 3 step 1 and it would still be correct.

  • There is no update statement to write: downTo decreases our number by 1 every time (add step to skip numbers).


Assignment

Let's print all numbers from 5 through -5 in decreasing order.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check