🎓 A1Learner
🔍
0 of 50 lessons completed

Scala For Loops

A for loop repeats a block once for each value in a sequence. A range is a sequence of numbers made with to or until.

to includes the end value

The loop takes each number from 1 to 3 in turn. The 3 prints, which proves the end value is included.

@main def main(): Unit =
  for i <- 1 to 3 do
    println(i)

until leaves the end value out

This range also starts at 1 and names 3 as its end. The 3 never prints, which proves until leaves it out.

@main def main(): Unit =
  for i <- 1 until 3 do
    println(i)

by 3 steps over numbers

The step makes the value jump by 3 in each round. The loop lands exactly on the end value of 10.

@main def main(): Unit =
  for i <- 1 to 10 by 3 do
    println(i)

Example

@main def main(): Unit =
  for i <- 2 to 8 by 2 do
    println(i)
  for i <- 3 to 1 by -1 do
    println(i)
  println("Go")

Key points

  • Generator: the part i <- 1 to 5 gives the loop one value at a time.
  • To: to includes the end value in the range.
  • Until: until leaves the end value out of the range.
  • Do: the word do marks the end of the loop line in Scala 3.
  • Step: by sets how far the value jumps in each round.
  • Countdown: a step of -1 makes the values go down.

In this example, the first loop steps by 2 from 2 to 8, printing the even numbers. The second loop steps by -1, counting down from 3 to 1. The word Go prints once after both loops finish.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does this loop print? for i <- 0 until 3 do println(i).