Related Tags

c++
sum
squares
communitycreator

# How to calculate the sum of squares of the first n numbers in C++ Onyejiaku Theophilus Chidalu

## Overview

The sum of the squares of the first n natural numbers involves calculating the sum of squares from 1 to n.

Mathematically, the formula for the sum of squares of the first n natural numbers is given as follows:

$\sum_{i=1}^n$ $i^{2}$ = $1^{2}$ + $2^{2}$ + $3^{2}$ + $4^{2}$ + … + $n^{2}$

In this shot, we will write a simple program that calculates the sum of the squares of the first n natural numbers.

## Code

We will solve this problem using the while and for loops.

### Method 1: while loop

The following code calculates the sum of the first n natural numbers using the while loop:

#include<iostream>
using namespace std;

int main() {
int sum = 0, i = 1, n = 5;

// iterating i from 1 to n
while (i <= n)
{
// finding square of i and adding to sum
sum += i * i;
i++;
}

// displaying the final result
cout << "The sum of squares of first " << n << " numbers is: " << sum << endl;
return 0;
}

### Explanation

The while loop provides a condition that while i is less than n, the program will calculate the sum of squares using an increment for the squares sequentially. So it provides an increment in line 10 and also an increment of the numbers (preceding the value of n) by one in line 11.

### Method 2: for loop

The following code calculates the sum of the first n natural numbers using a for loop:

#include<iostream>
using namespace std;

int main() {
int sum = 0, n = 5;

// iterating i from 1 to n
for (int i = 1; i <= n; i++)
{
// finding square of i and adding to sum
sum += i * i;
}

// displaying the final result
cout << "The sum of squares of first " << n << " numbers is: " << sum << endl;
return 0;
}

This is how we can successfully create a program to compute the sum of squares of the first n natural numbers with a for loop.

RELATED TAGS

c++
sum
squares
communitycreator

CONTRIBUTOR Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 