Home > Backend Development > C++ > body text

Sum of first n natural numbers in C program

PHPz
Release: 2023-08-29 14:29:07
forward
1299 people have browsed it

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
Copy after login

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
Copy after login

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;
}
Copy after login

Output

The sum of sum of natural number till 4 is 5
Copy after login

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
Copy after login

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;
}
Copy after login

Output

the sum of sum of natural number till 4 is 60
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template