Start learning free

LESSON 134 OF 347 · LOOPS & GLOBAL VARIABLES

Sum of Numbers in C#: 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

    C# · LOOPS & GLOBAL VARIABLES

    Sum Of Numbers in C#, explained

    What the exercise asks

    Compute the sum of all whole numbers from 14 to 73, using a for loop, and print the result. The technique is the accumulator pattern: a variable starts at 0, and each pass of a loop adds one more value to it. When the loop ends, the variable holds the total.

    The accumulator pattern

    Almost every "total up some values" problem has the same three parts:

    1. A variable that holds the running total, declared before the loop and set to 0. Zero is the neutral starting value for addition: with nothing added yet, the total is 0.
    2. A loop that produces the values. Here that is a for loop whose counter runs from 14 to 73.
    3. An update inside the loop that folds the current value into the total.

    The total must be declared outside the loop. A variable declared inside the loop body is created fresh on every pass, so it could never accumulate anything.

    The for loop

    A C# for loop has three parts in its header, separated by semicolons:

    for (int i = 14; i <= 73; i++) {
        // body
    }
    
    • int i = 14 runs once at the start and declares the counter.
    • i <= 73 is checked before every pass. When it becomes false, the loop ends.
    • i++ runs after every pass and adds 1 to i.

    The range 14 to 73 includes both ends, which is why the condition is <=. With < 73 the last value, 73, would be left out.

    The exercise step by step

    1. Declare the total: int sum = 0;.
    2. Write the loop with i running from 14 through 73.
    3. Add i to sum inside the body, with sum += i;. The operator += is shorthand for sum = sum + i.
    4. Print the total after the loop, with Console.WriteLine(sum);. The print must come after the closing brace. Inside the loop, it would print a running total on every pass.
    int sum = 0;
    for (int i = 14; i <= 73; i++) {
        sum += i;
    }
    Console.WriteLine(sum);
    

    The program prints:

    2610
    

    Checking the answer with arithmetic

    You can verify 2610 without running the code. The range has 73 - 14 + 1 = 60 numbers. Pair the smallest with the largest: 14 + 73 = 87, and the next pair, 15 + 72, is 87 too. Every pair adds up to 87, and there are 30 pairs, so the total is 30 * 87 = 2610. The loop reaches the same answer by brute force, one number at a time.

    C# gotchas

    • int overflow is silent. An int holds values up to 2,147,483,647. If a total grows beyond that, C# wraps around to a negative number without any warning by default. For this range the total is far below the limit. For larger sums, declare long sum = 0;.
    • Semicolons in the header. The header needs exactly two, between its three parts. A semicolon right after the closing parenthesis, as in for (...);, makes the loop body empty and detaches the braces below from it.
    • The scope of i. The counter exists only inside the loop. Using i after the closing brace is a compile error.
    • Uninitialised variables. C# refuses to compile code that reads a local variable before it has a value. Writing int sum; and then sum += i; gives an error, so the = 0 is required.

    Common mistakes

    • Starting at 0 or 1 instead of 14, which adds extra numbers.
    • Stopping at 72 by using < 73.
    • Writing sum = i instead of sum += i, which keeps only the last value (73).
    • Printing inside the loop, which produces 60 lines instead of one.

    Key takeaways

    • An accumulator starts at 0, outside the loop, and is updated inside the loop.
    • A for header has an initialiser, a condition and an update, and the condition decides whether the end value is included.
    • sum += i means sum = sum + i.
    • Print once, after the loop, to show the final total.
    • Use long when a sum might pass about two billion.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free