Sum of squares of the first n even numbers in C Program


The sum of squares of the first n even numbers means that, we first find the square and add all them to give the sum.

There are two methods to find the sum of squares of the first n even number

Using Loops

We can use loops to iterate from 1 to n increase number by 1 each time find the square and add it to the sum variable −

Example

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

Output

Sum of first 12 natural numbers is 2600

The complexity of this program increase by order 0(n). So, for big values of n, code takes time.

Using Mathematical formula

To deal with this problem a mathematical formula is derived which is Sum of even natural number is 2n(n+1)(2n+1)/3

Example

#include <iostream>
using namespace std;
int main() {
   int n = 12;
   int sum = (2*n*(n+1)*(2*n+1))/3;
   cout <<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0;
}

Output

Sum of first 12 natural numbers is 2600

Updated on: 08-Aug-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements