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)
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.
#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; }
The sum of sum of natural number till 4 is 5
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
#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; }
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!