Home  >  Article  >  Backend Development  >  Sum of first n natural numbers in C program

Sum of first n natural numbers in C program

PHPz
PHPzforward
2023-08-29 14:29:071241browse

Sum of first n natural numbers in C program

The concept of finding the sum of the sum of integers is found like this, first, we will find the sum of the numbers from 1 to n and then add all the sums to get A value that is the sum of the sums we want.

For this problem, we are given a number n and we want to find the sum of sum. Let us give 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

There are two ways to find the sum of the sum of n natural numbers:

Method 1 - Use a for loop (inefficient)

Method 2 - Use mathematical formulas (efficient)

Method 1 - Use for Loop

In this method we will use two for loops to find the sum of the sum. The inner loop finds the sum of natural numbers and the outer loop adds this sum to sum2 and increments 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 Mathematical Formula

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

The mathematical formula for solving the sum of n natural numbers is:

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

Example

’s Chinese translation is:

Example

#include <stdio.h>
int main() {
   int n = 4;
   int sum = (n*(n+1)*(n+2))/2;
   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 60

The above is the detailed content of Sum of first n natural numbers in C program. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete