Start learning free

LESSON 135 OF 347 · LOOPS & GLOBAL VARIABLES

Sum of Numbers in C#: Fixing the Buggy Loop

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 (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

    C# · LOOPS & GLOBAL VARIABLES

    Buggy Code Numbers Sum in C#, explained

    What the code is supposed to do

    ComputeSum(int n) returns the sum of the whole numbers from 0 up to n - 1. For ComputeSum(4) that is 0 + 1 + 2 + 3 = 6, and MainFunction prints the result. The starter code prints 16 instead.

    public int ComputeSum(int n) {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += n;
        }
        return sum;
    }
    

    What goes wrong

    The number 16 is the clue: it equals 4 + 4 + 4 + 4. The loop runs four times, and on each pass it adds n, which is the method's argument and stays 4 the whole time. The total is therefore n * n, not the sum of the numbers below n.

    The loop counter i is the value that changes from one pass to the next: it is 0, then 1, then 2, then 3. The sum is supposed to collect those values, but the body never mentions i, so the counter does its job of repeating the body and contributes nothing to the total.

    Fixing it step by step

    1. Notice that the loop already visits the right numbers. With i = 0 and i < n, the counter takes the values 0 to n - 1, which is exactly the range the task wants.
    2. Change what is added. Replace sum += n with sum += i.
    3. Leave the rest alone. The initial value, the loop header and the return are correct.

    The fixed code in C#

    public int ComputeSum(int n) {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += i;
        }
        return sum;
    }
    
    public void MainFunction() {
        Console.WriteLine(ComputeSum(4));
    }
    

    Tracing ComputeSum(4), the value of sum after each pass is:

    • i = 0: sum is 0.
    • i = 1: sum is 1.
    • i = 2: sum is 3.
    • i = 3: sum is 6.

    The loop ends because i becomes 4, which is not less than n. The method returns 6, and the program prints:

    6
    

    Notes on the C# code:

    • The upper bound is exclusive. With i < n, the value n itself is never added. The lesson asks for the sum up to n - 1, so this matches.
    • The method returns, and MainFunction prints. The return type is int, so the caller gets the value and decides what to do with it. Console.WriteLine accepts an int directly.
    • PascalCase names. The method is ComputeSum. A lowercase computeSum is a different, undeclared name in C#.
    • Overflow. An int that gets too large wraps to a negative value without an error. For the sum of 0 to n - 1, this starts to happen once n reaches 65,537. The lesson's tests use small values.

    How to find this kind of bug

    When the output is wrong, compare it with the expected value and look for a pattern. Here 16 is 4 * 4, which points at "n added n times". A second technique is to write out the first pass or two by hand with real values. On the first pass the buggy code does sum += 4, while the correct one should do sum += 0. The mismatch shows up at once.

    Common mistakes

    • Changing the loop instead of the body. Starting at 1 or using <= changes which numbers are visited. With <= and sum += i, the method returns 10 for 4, not 6.
    • Replacing sum instead of adding to it. Writing sum = i keeps only the last number, 3.
    • Using the formula blindly. The closed form for 0 + ... + (n - 1) is n * (n - 1) / 2. It is correct, but the lesson practises the loop, so keep the accumulator.

    Checking your fix

    Run the code. The output should be 6. Also check by hand that ComputeSum(0) and ComputeSum(1) both return 0: the first never enters the loop, and the second adds only 0.

    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