Start learning free

LESSON 122 OF 348 · WHILE LOOPS & FOR LOOPS

Looping In Reverse in Scala in Scala

Lesson

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

for (i <- 7 to 3 by -1) {
	println(i)
}

The output of this code is:

7
6
5
4
3

Let's break down this code:

  • The range starts at 7.

  • to 3 means the range includes 3.

  • by -1 means we decrease our number by 1 every time.


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

    Looping In Reverse in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free