Start learning free

LESSON 135 OF 348 · LOOPS & GLOBAL VARIABLES

Sum of Numbers in TypeScript: Adding a Range with 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

    TYPESCRIPT · LOOPS & GLOBAL VARIABLES

    Sum Of Numbers in TypeScript, explained

    What the exercise asks for

    The task is to compute the sum of all whole numbers from 14 to 73, both ends included, using a for loop, and then print the result to the console. There is no function to write: the code is a few statements at the top level of the file. The exercise introduces one of the most common loop patterns, the accumulator: a variable that starts at a neutral value and collects a little more on each pass of the loop.

    The idea: a running total

    Adding 60 numbers by hand means keeping a running total in your head: 14, then 14 + 15, then that plus 16, and so on. A loop does the same thing. You keep the total in a variable and update it for each number.

    The variable must start at 0, because 0 is the value that changes nothing when you add to it. If it started at any other number, that number would end up in the answer. The loop then visits 14, 15, ..., 73 and adds each one to the total. When the loop is over, the total holds the answer, and a final line prints it.

    The order matters: declare the total before the loop, add inside the loop, print after the loop. If the print were inside the loop, it would show 60 partial sums instead of one result.

    Step by step

    1. Declare the total. Write let sum: number = 0;. The keyword let makes a variable whose value can change, and the annotation says it holds a number. It has to be declared outside the loop. A variable declared inside the loop body is created fresh on every pass and is gone when the pass ends.
    2. Write the loop header. The loop has three parts: let i: number = 14 starts the counter at 14, the condition i <= 73 keeps going while the counter has not passed 73, and i++ adds 1 after each pass. The condition uses <= because 73 is part of the range. With < the loop would stop at 72.
    3. Add the counter to the total. Inside the body, sum += i; adds the current value of i to sum. It is short for sum = sum + i.
    4. Print the result. After the closing brace of the loop, console.log(sum); shows the total. The expected value is 2610.

    The solution in TypeScript

    let sum: number = 0;
    for (let i: number = 14; i <= 73; i++) {
        sum += i;
    }
    console.log(sum);
    

    Running this program prints:

    2610
    

    Checking the number

    You can verify 2610 without a loop. The numbers from 14 to 73 form a sequence of 60 terms (73 - 14 + 1), and the first and last add up to 14 + 73 = 87. Pairing the terms from both ends gives 30 pairs, each adding to 87, so the sum is 30 * 87 = 2610. The loop and the formula agree.

    The loop is worth learning anyway, because it works when the numbers to add are not a neat range, for example when they come from an array or only some of them should be counted.

    TypeScript details

    • Annotations are optional here. TypeScript infers the type number from the initial values 0 and 14, so let sum = 0; means the same. The lesson writes the types out to make them visible. They exist only for the compiler and are erased from the JavaScript that tsc writes.
    • let and const. Use let for a variable that changes, like sum and i. Declaring sum with const would make sum += i a compile error, because a const cannot be reassigned.
    • Scope of i. A variable declared with let in the loop header exists only inside the loop, so a console.log(i) after the loop is a compiler error. The total sum, declared outside, is visible both inside and after the loop.
    • One numeric type. Whole numbers and decimals are both number. Sums of whole numbers stay exact up to 2^53, so a total like this one is no problem.
    • += and ++. They are shorthands for adding to a variable. i++ adds 1 to i and is the usual way to step a counter.

    Common mistakes

    • Stopping one short. With i < 73 the loop leaves out 73, and the program prints 2537 instead of 2610.
    • Starting one late. Beginning at 15 leaves out 14 and prints 2596.
    • Declaring sum inside the loop. The total would restart at 0 on every pass, and it would also not be visible to the print after the loop.
    • Printing inside the loop. The output would be 60 lines of growing sums instead of one result.
    • Using = instead of +=. With sum = i, each pass replaces the total instead of adding to it, and the program prints 73, the last value.
    • Forgetting to initialise. A sum without the starting value 0 is undefined, and adding a number to undefined gives NaN.

    Key takeaways

    • An accumulator is declared before the loop, starts at a neutral value (0 for sums), and is updated inside the loop.
    • A for loop has three parts: the start, the condition and the step. Use <= when the last number belongs to the range.
    • Print the result once, after the loop.
    • The sum of the numbers from 14 to 73 is 2610.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free