Through this program you can learn how to calculate the sum of natural numbers. We know 1, 2, 3... these are natural positive numbers. This program takes an input from the user up to the number of natural numbers to be calculated.
Suppose if the user inputs 3 then the output will be 1+2+3=6
We have taken three variables i, n and sum in this program. In the beginning, I assigned the value of sum to zero to eliminate the garbage problem. Then we take a natural number from the user through which we will calculate the natural value sum. Then we calculated the sum of natural numbers using a loop and printed the series of sums of natural numbers.
Suppose if the user inputs 3 then the output will be 1+2+3=6
Calculate the Sum of Natural Numbers
#include<stdio.h>
int main(){
int i,n,sum=0;
printf("Enter a number: \n");
scanf("%d",&n);
for(i=1;i<=n;i++){
sum=sum+i;
printf("%d ",sum);
}
printf("\n");
printf("The sum is: %d\n",sum);
return 0;
}
Output
Enter a number:
7
1 3 6 10 15 21 28
The sum is: 28
We have taken three variables i, n and sum in this program. In the beginning, I assigned the value of sum to zero to eliminate the garbage problem. Then we take a natural number from the user through which we will calculate the natural value sum. Then we calculated the sum of natural numbers using a loop and printed the series of sums of natural numbers.
Tags:
C Program