Start learning free

LESSON 134 OF 414 · LOOPS & CONDITIONALS

Print Positive Negative in Scala: Fixing the Buggy Code

Practice Read the full explanation

Inside the code editor we've tried to write a function that takes an array nums as argument and for every number in the array:

  • prints "negative" if that number is less than zero

  • or prints the number itself, if the number is greater than or equal to zero

So when we called the function for [2, -12, 0, 4, -5, 3], we expected it to print:

2
negative
0
4
negative
3

but it seems like we made some mistakes because when we run our code, it produces this output:

positive
2
-12
0
positive
4
-5
positive
3

Assignment:

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

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · LOOPS & CONDITIONALS

    Buggy Code Print Positive Negative in Scala, explained

    What the code is supposed to do

    The function printPositiveAndNegative receives an Array[Int] named nums and prints one line for each element. A number below zero is replaced by the word negative. Any other number, zero included, is printed as it is. For [2, -12, 0, 4, -5, 3] the expected output is:

    2
    negative
    0
    4
    negative
    3
    

    The code you start with produces a different output: an extra positive line before each positive number, and the negative numbers printed as they are.

    def printPositiveAndNegative(nums: Array[Int]): Unit = {
        for (num <- nums) {
            if (num > 0) {
                println("positive")
            }
            println(num)
        }
    }
    
    // Do not change this code:
    def mainFunction(): Unit = {
        printPositiveAndNegative(Array(2, -12, 0, 4, -5, 3))
    }
    

    What goes wrong

    There are three separate problems in the five lines of the loop body.

    1. The condition picks the wrong numbers. num > 0 is true for positive numbers, but the special message belongs to numbers less than zero. This is why 2, 4 and 3 get an extra line while -12 and -5 get nothing.
    2. The message is the wrong word. The task asks for negative, and the code prints positive.
    3. The last println runs every time. It sits after the if, not inside a branch, so every number is printed even when the message was already printed for it. A number that gets the message should not also be printed.

    So for 2 the code prints positive and then 2. For -12 it skips the message and prints -12. For 0 it prints just 0, which happens to be right, because zero is not greater than zero and not less than zero either.

    Fixing it step by step

    1. Change the test to num < 0. Now the branch is entered only for numbers below zero. Zero stays out of it, as the task requires.
    2. Print "negative" in that branch. Replace the text of the existing println.
    3. Put the number printing in an else branch. The else runs exactly when the condition is false, which is when the number is zero or positive. Now every element produces exactly one line.

    The fixed code in Scala

    def printPositiveAndNegative(nums: Array[Int]): Unit = {
        for (num <- nums) {
            if (num < 0) {
                println("negative")
            } else {
                println(num)
            }
        }
    }
    
    
    def mainFunction(): Unit = {
        printPositiveAndNegative(Array(2, -12, 0, 4, -5, 3))
    }
    

    The output for the example array is:

    2
    negative
    0
    4
    negative
    3
    

    Some details of this Scala code:

    • Looping over an array. for (num <- nums) visits the elements in order, binding each one to num. No index is needed when the position doesn't matter.
    • Array(...) builds an array. Array(2, -12, 0, 4, -5, 3) creates an Array[Int], with the element type inferred from the numbers.
    • println accepts both types. The two branches print a String and an Int, and both work with the same function.
    • Negative numbers print with a minus sign. The output of println(-12) would be -12, which is why the original code showed that value on its own line.

    Common mistakes

    • Using num <= 0. That would print negative for zero. The task wants the number itself when it is greater than or equal to zero.
    • Keeping the final println(num) outside the branches. Negative numbers would then print twice, as negative followed by the number.
    • Checking num > 0 in the if and swapping the branches. This fails for zero: it would go to the branch for non-positive numbers and print negative for it.
    • Changing the call in mainFunction. The lines below the comment stay as they are.

    Checking your fix

    Run the code in the editor above and compare the six lines of output with the list at the top. The 0 in the middle of the array is the value worth checking: it must appear as a plain 0.

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free