Start learning free

LESSON 110 OF 414 · FOR LOOPS - LOOPING OVER ARRAYS

Why For Loops in Scala: The Cost of Repeating Code

Lesson Read the full explanation

For loops are very useful for iterating over sequences of elements.

To understand the value of for loops, let’s take some time to see how frustrating our life would be if a repeated task required us to type out the same code every single time.


Example: Greeting our friends

Imagine this: We have an array of friends and we want to greet each of them using a message template.

If we only use println(), our program might look like this:

val friends = Array("Andy", "Mircea", "David", "Mary")

println("Hey, " + friends(0))
println("Hey, " + friends(1))
println("Hey, " + friends(2))
println("Hey, " + friends(3))

That’s ugly, but still manageable. After all, we’re writing only 4 lines of code and most probably copying and pasting a few times.

Now imagine if we had 10, 100 friends? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.

We’ll learn how for loops come to our rescue in the next lesson. But for now, let’s gain an appreciation for them.


Assignment
Follow the Coding Tutorial to see how frustrating our life is without for loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · FOR LOOPS - LOOPING OVER ARRAYS

    Why For Loops in Scala, explained

    The task without a loop

    A program often needs to do the same thing for every element of a collection: greet each friend, print each item, add up each price. Before learning the tool for that, it helps to feel the problem it solves. This lesson writes the repetitive version on purpose.

    The starting code has an array of four fruits:

    val fruits = Array("banana", "orange", "pear", "kiwi")
    

    The goal is to print I eat banana, I eat orange, and so on, one line per fruit, using only println.

    Step by step

    1. Read an element by its index. Scala indexes an array with parentheses, not square brackets: fruits(0) is "banana". Indices start at 0, so the four fruits are fruits(0) through fruits(3).
    2. Join the text and the element. The + operator glues strings together, so "I eat " + fruits(0) produces I eat banana. The space at the end of "I eat " is part of the text.
    3. Print it and repeat for each index. One println per fruit, with the index changed each time.
    val fruits = Array("banana", "orange", "pear", "kiwi")
    
    println("I eat " + fruits(0))
    println("I eat " + fruits(1))
    println("I eat " + fruits(2))
    println("I eat " + fruits(3))
    

    The program prints:

    I eat banana
    I eat orange
    I eat pear
    I eat kiwi
    

    Why this does not scale

    Four lines are tolerable. The trouble shows up as the data grows or changes:

    • More elements, more lines. For 100 fruits you would write 100 nearly identical lines, one for each index.
    • The code is tied to the array's length. If the array has five elements, the fifth is silently never printed. If it has three, the line fruits(3) throws an ArrayIndexOutOfBoundsException and the program stops.
    • Copy and paste invites mistakes. Forgetting to change one index prints the same fruit twice. Changing the wording means editing every line, and missing one makes the output inconsistent.
    • The array might not be known in advance. If the fruits come from a file or from the user, you can't know how many lines to write.

    Every one of these problems comes from one fact: the code repeats a pattern by hand, and only the index changes. The pattern is "print I eat and the element at position i", for each valid i.

    The idea behind a loop

    A for loop lets you write the pattern once and have Scala repeat it for every element. The next lesson covers the syntax, but here is the shape of it so you can see what the repetition above turns into:

    for (fruit <- fruits) {
      println("I eat " + fruit)
    }
    

    This prints the same four lines. It also works unchanged for an array of 4, 5 or 100 fruits, and for an empty array, where it simply prints nothing. The loop takes care of the indices, so there is no fruits(3) to get wrong.

    Key takeaways

    • Scala arrays are indexed with parentheses and start at 0.
    • Repeating a statement by hand with a different index each time is slow to write and easy to get wrong.
    • Hand-written indices break when the array's length changes.
    • For loops exist to write the repeated pattern once.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free