Start learning free

LESSON 124 OF 414 · WHILE LOOPS & FOR LOOPS

The For Loop in Scala: Looping Over a Range

Lesson Read the full explanation

Scala for loops commonly iterate over a range.

The range decides where the loop starts, where it stops, and how it changes:

for (item <- range) {
	instruction1
	instruction2
	...
}

Let's break down each component:

  • The loop variable takes each value from the range.

  • The <- operator connects the loop variable to the range.

  • The range decides which values are visited.


Example:

for (i <- 0 until 4) {
	println("Hello world!")
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The range starts at 0.

  • until 4 means the range stops before 4.

  • So i takes the values 0, 1, 2, and 3.


This is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 4 true? <=> Is 0 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello world!".
	c. next value of i => i = 1
	
2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello world!".
	c. next value of i => i = 2
	
3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello world!".
	c. next value of i => i = 3
	
4. Fourth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello world!".
	c. next value of i => i = 4

5. Fifth iteration:
	a. Is i < 4 true? <=> Is 4 < 4 true? No.
	b. Exit the loop.

Assignment

Let's print "I promise to learn coding." 5 times using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · WHILE LOOPS & FOR LOOPS

    The For Loop in Scala, explained

    What a Scala for loop is

    A Scala for loop doesn't have the three-part header of C or Java. It takes each value of a collection in turn, and for counting the collection is a range:

    for (item <- range) {
        // instructions that run once per value
    }
    

    The pieces are:

    • item is the loop variable. On each pass it holds the next value of the range.
    • <- reads as "taken from". The part to its right is called a generator.
    • range decides which values are visited, and therefore how many times the body runs.

    You never declare the loop variable with var and never update it yourself. It is a fresh val on each pass, so assigning to it inside the body is a compile error.

    Ranges with until

    The expression 0 until 4 builds a range that starts at 0 and stops before 4. Its values are 0, 1, 2 and 3:

    for (i <- 0 until 4) {
        println("Hello world!")
    }
    

    This prints Hello world! four times. The variable i is not used in the body, which is fine. Here it only makes the body run once for each value.

    Because until excludes its end, 0 until n has exactly n values, which is why it is the usual way to repeat something n times. The related word to includes its end: 0 to 4 has five values, 0 through 4. Mixing the two up is the most common off-by-one error with Scala ranges.

    What happens on each pass

    For 0 until 4 the loop works like this:

    1. i is 0. The body runs.
    2. i is 1. The body runs.
    3. i is 2. The body runs.
    4. i is 3. The body runs.
    5. The range has no more values, so the loop ends.

    There is no condition to check and no counter to increase by hand, so a range-based loop can't become an infinite loop through a forgotten update.

    The assignment: print a sentence 5 times

    The task is to print "I promise to learn coding." five times.

    1. Write the loop header. Use for (i <- 0 until 5). The range has five values, 0 to 4, so the body will run five times.
    2. Print the message inside the body with println. The body runs once per value, so one println line produces five lines of output.
    for (i <- 0 until 5) {
        println("I promise to learn coding.")
    }
    

    The output is the sentence on five separate lines.

    Common mistakes

    • Using to instead of until. 0 to 5 has six values and prints the message six times.
    • Writing = instead of <-. The generator needs the arrow. for (i = 0 until 5) doesn't compile.
    • Trying to change the loop variable. A line such as i += 1 inside the body is rejected, because i can't be reassigned. To change the step, change the range.
    • Writing i++. Scala has no ++ operator, and the range already moves forward for you.

    Key takeaways

    • for (x <- range) runs its body once for each value of the range.
    • a until b stops before b; a to b includes b.
    • The loop variable is created by the loop and can't be reassigned.
    • 0 until n repeats a block exactly n times.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free