Sum of squares of the first n even numbers in C Program

The sum of squares of the first n even numbers means we calculate the square of each even number (2, 4, 6, 8, ..., 2n) and add them together. For example, for n=3, we compute 2² + 4² + 6² = 4 + 16 + 36 = 56.

There are two methods to find the sum of squares of the first n even numbers −

Syntax

// Using loop approach
sum = 0;
for (i = 1; i <= n; i++) {
    sum += (2 * i) * (2 * i);
}

// Using mathematical formula
sum = (2 * n * (n + 1) * (2 * n + 1)) / 3;

Method 1: Using Loops

We can use loops to iterate from 1 to n, generate each even number (2*i), find its square, and add it to the sum variable −

#include <stdio.h>

int main() {
    int sum = 0, n = 12;
    
    for (int i = 1; i <= n; i++) {
        sum += (2 * i) * (2 * i);
    }
    
    printf("Sum of squares of first %d even numbers is %d<br>", n, sum);
    return 0;
}
Sum of squares of first 12 even numbers is 2600

The time complexity of this approach is O(n), which means for large values of n, the execution time increases linearly.

Method 2: Using Mathematical Formula

To optimize the solution, we can use the mathematical formula: Sum = 2n(n+1)(2n+1)/3. This formula gives us the result in constant time −

#include <stdio.h>

int main() {
    int n = 12;
    int sum = (2 * n * (n + 1) * (2 * n + 1)) / 3;
    
    printf("Sum of squares of first %d even numbers is %d<br>", n, sum);
    return 0;
}
Sum of squares of first 12 even numbers is 2600

Comparison

Method Time Complexity Space Complexity Best For
Loop Method O(n) O(1) Understanding the concept
Formula Method O(1) O(1) Large values of n

Conclusion

The mathematical formula approach is more efficient with O(1) time complexity, making it ideal for large values of n. Both methods produce the same result, but the formula method is significantly faster for computational purposes.

Updated on: 2026-03-15T11:22:05+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements