- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

#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

- Related Questions & Answers
- Python Program for Sum of squares of first n natural numbers
- Sum of squares of first n natural numbers in C Program?
- Java Program to calculate Sum of squares of first n natural numbers
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers
- Difference between sum of the squares of and square of sum first n natural numbers.
- C Program for the cube sum of first n natural numbers?
- Program for cube sum of first n natural numbers in C++
- Sum of first n natural numbers in C Program
- Average of Squares of n Natural Numbers?
- Sum of sum of first n natural numbers in C++
- Java Program to cube sum of first n natural numbers
- Sum of square-sums of first n natural numbers
- Sum of squares of the first n even numbers in C Program

Advertisements