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:
= + + + + … +
In this shot, we will write a simple program that calculates the sum of the squares of the first n natural numbers.
We will solve this problem using the while
and for
loops.
while
loopThe 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 nwhile (i <= n){// finding square of i and adding to sumsum += i * i;i++;}// displaying the final resultcout << "The sum of squares of first " << n << " numbers is: " << sum << endl;return 0;}
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.
for
loopThe 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 nfor (int i = 1; i <= n; i++){// finding square of i and adding to sumsum += i * i;}// displaying the final resultcout << "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.