Start learning free

LESSON 136 OF 347 · LOOPS & GLOBAL VARIABLES

Sum of Squares in C#: A Running Total with a for Loop

Practice Read the full explanation

Given a non-negative integer n, compute and return the sum of
12 + 22 + 32 + ... + n2

Example:

Input: n = 3

Output: 14

Explanation:
12 + 22 + 32 = 1 + 4 + 9 = 14
Hints:

Where should we store this sum as we compute it?

We can use a variable sum, initially equal to 0. We have to iterate through the numbers 1 to n. How can we do this?

Let's use a for loop and a variable i to iterate through the numbers 1 to n. What should we do inside this loop?

Inside the loop, all we should do is add i * i to sum.
When the loop terminates, the answer lies in sum.

STEP 1 OF 4
    Ctrl + Enter to check

    C# · LOOPS & GLOBAL VARIABLES

    Sum Of Squares in C#, explained

    Problem overview

    The method SumOfSquares(int n) takes a non-negative integer n and returns 1² + 2² + ... + n². For n = 3 the sum is 1 + 4 + 9 = 14. For n = 0 there is nothing to add, so the result is 0.

    Approach: accumulate one square per pass

    The task has the shape of a running total: keep a variable sum, visit the numbers 1 to n in turn, and add the square of each to it. The loop counter supplies the numbers, and the body turns each one into its square and adds it. When the loop is done, sum holds the answer.

    There is also a closed-form formula, n * (n + 1) * (2 * n + 1) / 6, but the lesson is about loops and accumulators, so it uses the direct approach. The loop version also makes each step visible, which is useful for debugging.

    Step by step

    1. Declare int sum = 0;. Zero is right because nothing has been added yet.
    2. Write the loop header as for (int i = 1; i <= n; i++). It starts at 1, since 0² adds nothing and the sum begins at 1². The condition is <= so that n itself is included.
    3. Add the square. Inside the loop, write sum += i * i;. The operator += adds the right side to the variable, so this means sum = sum + i * i. Multiplication happens before the addition.
    4. Return sum after the loop.

    The solution in C#

    class Solution {
        public int SumOfSquares(int n) {
            int sum = 0;
            for (int i = 1; i <= n; i++) {
                sum += i * i;
            }
            return sum;
        }
    }
    

    Tracing n = 3, the value of sum after each pass is:

    • i = 1: sum is 0 + 1 = 1.
    • i = 2: sum is 1 + 4 = 5.
    • i = 3: sum is 5 + 9 = 14.

    Then i becomes 4, the condition i <= n fails, and the method returns 14.

    Some C# details:

    • There is no power operator. C# has no ** or ^ for powers. ^ is the bitwise XOR operator, which gives unrelated results. Multiplying i * i is the simplest way to square an integer. Math.Pow exists, but it returns a double and would need a cast to int.
    • The loop variable is local. i exists only inside the loop. The accumulator sum is declared outside, so it survives after the loop and can be returned.
    • The class and method names are Solution and SumOfSquares. Code ported from other languages often has sumOfSquares in lowercase, which does not match.

    Complexity

    Time: O(n). The loop runs n times, and each pass does a multiplication and an addition.

    Space: O(1). The method keeps two integers, sum and i.

    Edge cases and common mistakes

    • n = 0. The loop starts at 1, the condition 1 <= 0 is false at once, and the method returns 0.
    • n = 1. The loop runs once and returns 1.
    • Integer overflow. An int holds at most 2,147,483,647, and C# wraps silently when a result goes beyond that. The sum of squares passes the limit at n = 1861: SumOfSquares(1860) is 2146682110, but SumOfSquares(1861) would give a negative number. In the largest range you would declare sum as a long and write sum += (long)i * i. Note that i * i is computed in int first, so the cast has to be on one operand and not on the product.
    • Using < n. That leaves out n². For n = 3 the result would be 5.
    • Starting at 0. This is harmless for the result (0² is 0), but it adds a useless pass.
    • Adding i instead of i * i. That computes the plain sum 1 + 2 + 3 = 6.
    • Squaring the total. sum += i followed by sum * sum at the end computes the square of the sum, which is a different quantity (36 for n = 3).

    Testing

    • n = 3 gives 14.
    • n = 0 gives 0.
    • n = 1 gives 1.
    • n = 4 gives 30 (1 + 4 + 9 + 16).
    • n = 10 gives 385.
    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