Start learning free

LESSON 119 OF 414 · WHILE LOOPS & FOR LOOPS

Why Loops? Repeating Code in Scala

Lesson Read the full explanation

Loops are probably the most powerful tool a programming language can offer. You can run the same code multiple times by using a loop.

To really understand their value, 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.

Imagine this: A student made a mistake and the teacher asked them to print I made a mistake 5 times to the console.

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

println("I made a mistake")
println("I made a mistake")
println("I made a mistake")
println("I made a mistake")
println("I made a mistake")

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

Now imagine if we come back to this program and we wanted to print the message for 10, 100, 100000 times? It would take an extremely long time and by the end, we could still end up with inconsistencies and mistakes.

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


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    SCALA · WHILE LOOPS & FOR LOOPS

    Why Loops in Scala, explained

    The problem without loops

    Programs often repeat the same action. Suppose a student has to write I made a mistake five times. With only println, you write the statement five times:

    println("I made a mistake")
    println("I made a mistake")
    println("I made a mistake")
    println("I made a mistake")
    println("I made a mistake")
    

    Each line prints the text and moves to a new line, so the output is five identical lines. For five repeats this is ugly but manageable, and copy and paste makes it fast.

    Why this doesn't scale

    Now the count changes to 100, or to 100,000. Writing that many statements by hand is impractical, and a source file that long is impossible to read. Smaller changes are a problem too:

    • Editing the message means changing every copy. Miss one and the output is inconsistent.
    • Changing the count means adding or deleting lines and counting them.
    • The count may not be known when you write the program. If it depends on the data, such as the number of names in an array, you can't write the right number of statements in advance.

    The code is the same each time; only the number of repeats varies. A loop is the tool that expresses this: you write the statement once and tell the program how many times, or for how long, to run it.

    What loops give you

    Scala has two main loops, and the following lessons cover them:

    • the while loop repeats a block as long as a condition holds;
    • the for loop runs a block once for each element of a collection or for each number in a range.

    A preview

    You don't need to understand this yet, but here is the same idea with a loop, using three repeats:

    for (i <- 1 to 3) println("I made a mistake")
    
    I made a mistake
    I made a mistake
    I made a mistake
    

    The text appears once in the source. To repeat it 100,000 times, you would change the 3, and the message stays in a single place, so editing it means one change. A while loop reaches the same result by repeating a block as long as a condition holds, and the next lessons build both loops step by step.

    The exercise

    This lesson has you feel the problem first. Print I promise to learn coding. five times using only println statements:

    println("I promise to learn coding.")
    println("I promise to learn coding.")
    println("I promise to learn coding.")
    println("I promise to learn coding.")
    println("I promise to learn coding.")
    

    The text must match exactly, including the capital I and the full stop at the end. Output:

    I promise to learn coding.
    I promise to learn coding.
    I promise to learn coding.
    I promise to learn coding.
    I promise to learn coding.
    

    The statements run one after another, from the first line down, so five statements give five lines. Notice how much of the code is the same line; that repeated part is what the next lessons remove.

    Key takeaways

    • Copying a statement to repeat it is slow, error-prone and impossible when the count is not known in advance.
    • A loop lets you write the repeated code once.
    • Scala's loops are while, which repeats while a condition is true, and for, which walks through a collection or a range.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free