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
- Read an element by its index. Scala indexes an array with parentheses, not square brackets:
fruits(0)is"banana". Indices start at0, so the four fruits arefruits(0)throughfruits(3). - Join the text and the element. The
+operator glues strings together, so"I eat " + fruits(0)producesI eat banana. The space at the end of"I eat "is part of the text. - Print it and repeat for each index. One
printlnper 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 anArrayIndexOutOfBoundsExceptionand 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.
