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


The sum of squares of the first n natural numbers is found by adding up all the squares.

Input - 5
Output - 55
Explanation - 12 + 22 + 32 + 42 + 52

There are two methods to find the Sum of squares of first n natural numbers −

Using Loops − the code loops through the digits until n and find their square, then add this to a sum variable that outputs the sum.

Example

#include <iostream>
using namespace std;
int main() {
   int n = 5;
   int sum = 0;
   for (int i = 1; i >= n; i++)
      sum += (i * i);
   cout <<"The sum of squares of first "<<n<<" natural numbers is "<<sum;
   return 0;
}

Output

The sum of squares of first 5 natural numbers is 55

Using Formula − To decrease the load on the program you can use mathematical formula to find the sum of squares on first n natural numbers. The mathematical formula is : n(n+1)(2n+1)/6

Example

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

Output

The sum of squares of 10 natural numbers is 385
raja
Published on 08-Aug-2019 08:01:53
Advertisements