Start learning free

LESSON 117 OF 414 · FOR LOOPS - LOOPING OVER ARRAYS

For Loop Execution Flow in Scala: Ordering the Lines

Practice Read the full explanation

Inside the code editor we've tried to write a program that should print:

What a nice day!
Hey, Andy
How are you?
Hey, Mike
How are you?
Hey, Mary
How are you?
Let's start the class!

but it seems like we made some mistakes because when we run our code, it does not compile.


Assignment:

Your task is to fix our code such that it will print the desired output.

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · FOR LOOPS - LOOPING OVER ARRAYS

    Buggy Code For Loops Execution Flow 3 in Scala, explained

    What the code is supposed to do

    The program should open with one line, greet each student with a question, and close with one line:

    What a nice day!
    Hey, Andy
    How are you?
    Hey, Mike
    How are you?
    Hey, Mary
    How are you?
    Let's start the class!
    

    The starter code doesn't compile:

    val students = Array("Andy", "Mike", "Mary")
    
    println("Let's start the class!")
    for (student <- students) {
        println("What a nice day!")
    }
    println("How are you?")
    println(s"Hey, $student")
    

    What goes wrong

    There are three kinds of problems at once.

    1. A compile error. The last line uses $student, but that variable exists only inside the loop's braces. After the closing brace the compiler reports Not found: student - did you mean students? and the program doesn't run.
    2. Lines that repeat but shouldn't. "What a nice day!" is inside the loop, so it would print three times, while the expected output has it once.
    3. Lines that should repeat but don't. The greeting and "How are you?" alternate in the expected output, once per student, so both belong in the loop body. In the starter they run only once, after the loop.

    Also, "Let's start the class!" is the first statement, but the expected output shows it last.

    Sorting each line into its place

    Read the expected output and ask of each line how many times it appears:

    • What a nice day! appears once, at the start: it goes before the loop.
    • Hey, ... and How are you? appear three times, in that order, for each student: they go inside the loop, in that order.
    • Let's start the class! appears once, at the end: it goes after the loop.

    Moving the greeting inside the loop also fixes the compile error, because the loop variable is now in scope where $student is used.

    Why the variable disappears after the loop

    The loop variable is created fresh for each pass and exists only for the body. After the closing brace there is no student any more, and it would not make sense to have one: the loop has gone through three students, and the code could not know which of them $student should mean. Any line that needs the current student has to be inside the body.

    The error message suggests students, which does exist, but it is the whole array. Interpolating it would print the array object instead of a name, so the right answer is to move the line, not to follow the suggestion.

    The fixed code in Scala

    val students = Array("Andy", "Mike", "Mary")
    
    println("What a nice day!")
    
    for (student <- students) {
        println(s"Hey, $student")
        println("How are you?")
    }
    
    println("Let's start the class!")
    

    The flow is: print the opening line, go through the array printing two lines per student, then print the closing line.

    Tracing the run

    The fixed program starts with the opening line. The loop then runs three passes. On the first, student is "Andy", so it prints Hey, Andy and then How are you?. The second and third passes do the same for Mike and Mary. When the array runs out, the loop ends and the last line prints. That gives exactly one opening line, three pairs of lines and one closing line, eight lines in all.

    The number of lines is a quick check. Expected output with three students has 1 + 3 * 2 + 1 = 8 lines; if yours has a different count, a statement is on the wrong side of a brace.

    Common mistakes

    • Swapping the order inside the loop. Printing "How are you?" first gives a question before each name.
    • Putting the opening line inside the loop. It would print before every student.
    • Fixing only the compile error. Moving one line to make it compile can leave the order wrong; check the whole output against the expected text.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free