Sum of squares of first n natural numbers in C Program?

In C programming, finding the sum of squares of the first n natural numbers means calculating 12 + 22 + 32 + ... + n2. This is a common mathematical problem that can be solved using different approaches.

Example: For n = 5, the sum is 12 + 22 + 32 + 42 + 52 = 1 + 4 + 9 + 16 + 25 = 55

Syntax

// Using loops
for(int i = 1; i <= n; i++) {
    sum += i * i;
}

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

Method 1: Using For Loop

This approach iterates through numbers from 1 to n, squares each number, and adds it to the sum −

#include <stdio.h>

int main() {
    int n = 5;
    int sum = 0;
    
    for (int i = 1; i <= n; i++) {
        sum += (i * i);
    }
    
    printf("The sum of squares of first %d natural numbers is %d<br>", n, sum);
    return 0;
}
The sum of squares of first 5 natural numbers is 55

Method 2: Using Mathematical Formula

The mathematical formula n(n+1)(2n+1)/6 provides a direct calculation without loops, making it more efficient −

#include <stdio.h>

int main() {
    int n = 10;
    int sum = (n * (n + 1) * (2 * n + 1)) / 6;
    
    printf("The sum of squares of first %d natural numbers is %d<br>", n, sum);
    return 0;
}
The sum of squares of first 10 natural numbers is 385

Comparison

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

Conclusion

Both methods solve the problem effectively, but the formula approach is preferred for larger values of n due to its constant time complexity. The loop method helps understand the underlying mathematical concept better.

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

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements