Start learning free

LESSON 121 OF 348 · WHILE LOOPS & FOR LOOPS

For Loops: Printing Numbers II in Scala in Scala

Lesson

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

We can print all even numbers from 2 through 10:

for (i <- 2 to 10 by 2) {
	println(i)
}

The output of this code is:

2
4
6
8
10

Let's break down this code:

  • The range starts at 2.

  • to 10 means the range includes 10.

  • by 2 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

    Printing Numbers 4 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