# C++ Program for Sum of squares of first n natural numbers?

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this problem we will see how we can get the sum of squares of first n natural numbers. Here we are using one for loop, that runs from 1 to n. In each step we are calculating square of the term and then add it to the sum. This program takes O(n) time to complete. But if we want to solve this in O(1) or constant time, we can use this series formula − ## Algorithm

### squareNNatural(n)

begin
sum := 0
for i in range 1 to n, do
sum := sum + i^2
done
return sum
end

## Example

Live Demo

#include<iostream>
using namespace std;
long square_sum_n_natural(int n) {
long sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i; //square i and add it with sum
}
return sum;
}
main() {
int n;
cout << "Enter N: ";
cin >> n;
cout << "Result is: " << square_sum_n_natural(n);
}

## Output

Enter N: 4
Result is: 30