Sum of first n natural numbers in C Program


The concept of finding the sum of sum of integers is found such that first, we will find the sum of numbers up to n and then add all the sums to get a value which will be the sum of sum which is our desired sum.

For this problem, we are given a number n up to which we have to find the sum of the sum. Let's take an example to find this sum.

n = 4

Now we will find the sum of numbers for every number from 1 to 4 :

Sum of numbers till 1 = 1
Sum of numbers till 2 = 1 + 2 = 3
Sum of numbers till 3 = 1 + 2 + 3 = 6
Sum of numbers till 4 = 1 + 2 + 3 + 4 = 10
Now we will find the sum of sum of numbers til n :
Sum = 1+3+6+10 = 20

For finding the sum of sum of n natural number, we have two methods :

Method 1: Using the for loops (inefficient)

Method 2: Using the mathematical formula (efficient)

Method 1: Using the for loops

In this method, we will use two for loops to find the sum of sum. The inner loop finds the sum of natural number and outer loop adds this sum to sum2 and increases the number by one.

Example

#include <stdio.h>
int main() {
   int n = 4;
   int sum=0, s=0;
   for(int i = 1; i< n; i++){
      for(int j= 1; j<i;j++ ){
         s+= j;
      }
      sum += s;
   }
   printf("the sum of sum of natural number till %d is %d", n,sum);
   return 0;
}

Output

The sum of sum of natural number till 4 is 5

Method 2: Using the mathematical formula

We have a mathematical formula for finding the sum of sum of n natural numbers. The mathematical formula method is an efficient method.

The mathematical formula to find the sum of sum of n natural number :

sum = n*(n+1)*(n+2)/6

Example

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

Output

the sum of sum of natural number till 4 is 20
raja
Published on 09-Aug-2019 11:18:30
Advertisements