Start learning free

LESSON 141 OF 414 · LOOPS & GLOBAL VARIABLES

Sum of Numbers in Scala: Fixing the Buggy Code

Practice Read the full explanation

Inside the code editor we've tried to write a function that takes a number n as argument and returns the sum of all numbers 0 through n - 1 (0 + 1 + 2 + ... + n - 1).

So when we called computeSum(4), we expected our code to print:

6

because 0 + 1 + 2 + 3 = 6. But it seems like we made some mistakes because when we run our code, it prints:

16

Assignment:

Your task is to fix our function such that it correctly computes and returns the desired sum.

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · LOOPS & GLOBAL VARIABLES

    Buggy Code Numbers Sum in Scala, explained

    What the code is supposed to do

    The function computeSum takes an Int named n and returns the sum of the whole numbers from 0 up to n - 1. For computeSum(4) that is 0 + 1 + 2 + 3 = 6, so the program should print 6. The code in the editor prints 16 instead:

    def computeSum(n: Int): Int = {
        var sum = 0
        for (i <- 0 until n) {
            sum += n
        }
        return sum
    }
    
    // Do not change this code:
    def mainFunction(): Unit = {
        println(computeSum(4))
    }
    

    Your job is to find the mistake and fix the function.

    What goes wrong

    The wrong output has a clue in it: 16 is 4 + 4 + 4 + 4. The loop runs four times, for i equal to 0, 1, 2 and 3, and each pass adds the same number to sum. That number is n, the function's parameter, which is 4 for the whole call. It never changes from one pass to the next.

    Here is the state after each pass for computeSum(4):

    PassiWhat is addedsum afterwards
    1044
    2148
    32412
    43416

    In general, the loop adds n to the total n times, so the result is always n * n. The loop variable i, which is the number that should be added, is never used.

    Fixing it step by step

    1. Identify what should be added. The sum is of the numbers 0, 1, 2, up to n - 1. Those are exactly the values i takes in 0 until n.
    2. Change the update. Replace sum += n with sum += i. Now each pass adds the current number instead of the fixed parameter.
    3. Leave the rest alone. The initial value 0, the range and the return sum are correct, and so is mainFunction.

    The fixed code in Scala

    def computeSum(n: Int): Int = {
        var sum = 0
        for (i <- 0 until n) {
            sum += i
        }
        return sum
    }
    
    
    def mainFunction(): Unit = {
        println(computeSum(4))
    }
    

    Now the passes add 0, 1, 2 and 3. The total goes 0, 1, 3, 6, and the program prints 6.

    Some Scala details behind this code:

    • Parameter versus loop variable. Inside the body, n keeps the value it was called with, and i takes a new value on each pass. Using the wrong one compiles fine, so only the output reveals the mistake.
    • until stops before n. 0 until n visits 0 to n - 1, which is the range the task describes. With 0 to n the sum would include n as well, giving 10 for computeSum(4).
    • var and +=. The total is a var because it changes on every pass, and sum += i is the short form of sum = sum + i.
    • return is optional. The last expression of a method is its value, so ending the method with just sum would work too. The lesson's code uses return, and it works the same.

    Common mistakes

    • Changing the range instead of the update. Switching to 0 to n or 1 until n doesn't fix the problem, because the loop would still add n repeatedly.
    • Printing n * n by hand. It would match the bug, not the task.
    • Adding i twice or adding i + 1. The sum then comes out too large. For computeSum(4), adding i + 1 gives 10.
    • Editing mainFunction. It is marked as code not to change.

    Checking your fix

    Run the code in the editor above. It should print 6. Other values to try mentally: computeSum(1) is 0, because the only number visited is 0, and computeSum(0) is 0 too, since the loop does not run. computeSum(10) is 45.

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