Start learning free

LESSON 140 OF 414 · LOOPS & GLOBAL VARIABLES

Sum of Numbers in Scala: Accumulating in a for Loop

Lesson Read the full explanation

Use a for loop to compute the sum of all numbers from 14 to 73.

Once computed, print this sum to the console.

STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · LOOPS & GLOBAL VARIABLES

    Sum Of Numbers in Scala, explained

    What the exercise asks for

    The exercise is to add up every whole number from 14 to 73, using a for loop, and then print the result. This is the standard accumulator pattern: a variable starts at a neutral value, a loop adds to it once per pass, and the total is used after the loop.

    The accumulator pattern in Scala

    Three parts make up the pattern:

    1. A variable that holds the running total, set to 0 before the loop. Zero is the neutral value for addition, so the first addition leaves the first number unchanged.
    2. A loop that visits each number.
    3. An update inside the loop that adds the current number to the total.

    In Scala the total must be declared with var, because its value changes. A variable declared with val can't be reassigned, and sum += i on a val is a compile error. Scala infers the type of var sum = 0 as Int from the literal, so no type annotation is needed.

    Ranges: to and until

    The loop header i <- 14 to 73 is a generator. It reads "for each i taken from the range 14 to 73". Scala has two range operators, and the difference between them is the usual source of off-by-one errors:

    • 14 to 73 includes both ends, so the last value is 73. It has 60 numbers.
    • 14 until 73 excludes the upper end, so the last value is 72. It has 59 numbers.

    The exercise says "from 14 to 73", with 73 included, so it needs to. With until the program would print 2537, which is 73 short of the right total.

    Step by step

    1. Declare the total. var sum = 0 creates an Int that starts at zero and can be changed.
    2. Write the loop. for (i <- 14 to 73) runs the body once for each number from 14 up to and including 73. The value of i is the current number.
    3. Add inside the loop. sum += i is shorthand for sum = sum + i. After the pass with i = 14, the total is 14. After i = 15 it is 29, and so on.
    4. Print after the loop. println(sum) sits outside the braces, so it runs once, when the loop is done. If it were inside, the program would print a running total on every pass instead of a single number.

    The solution in Scala

    var sum = 0
    for (i <- 14 to 73) {
        sum += i
    }
    println(sum)
    

    This prints 2610.

    Checking the answer

    The numbers from 14 to 73 form an arithmetic sequence. Its sum is the number of terms times the average of the first and last: 60 terms, and (14 + 73) / 2 = 43.5 on average, so 60 * 43.5 = 2610. The loop and the formula agree. In Scala, (14 to 73).sum gives the same value without writing a loop, but the loop shows what is happening step by step.

    Common mistakes

    • until instead of to. The range stops at 72 and the output is 2537.
    • Using val for the total. The compiler rejects the reassignment, because a val is fixed after it is created.
    • Starting the total at the wrong value. Starting at 1, for instance, would make every result too large by 1. Start at 0.
    • Printing inside the loop. The program would print 60 lines, with the last one the correct total.
    • Replacing += by =. Writing sum = i discards the earlier total on every pass, so the program ends with just 73.
    • Declaring the total inside the loop. A variable declared in the body is created again on every pass, and it isn't visible to the println after the loop.

    Key takeaways

    • An accumulator is a var that starts at a neutral value and is updated on each pass.
    • a to b includes b, while a until b excludes it.
    • sum += i is the short form of sum = sum + i.
    • Print the result after the loop, once, unless the exercise asks for the intermediate values.
    • The total for 14 through 73 is 2610.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free