Problem
Write a program in C to take the input (n) from the user and calculate the sum of all the natural numbers from 1 to n.
How to calculate the sum of natural numbers in C language ?
#include <stdio.h>
int main()
{
printf("Abundantcode.com coding sample\n");
int n, index, result = 0;
printf("Enter a positive number : ");
scanf("%d",&n);
for(index=1; index <= n; ++index)
{
result += index;
}
printf("Result = %d",result);
return 0;
}Output
Abundantcode.com coding sample
Enter a positive number : 4
Result = 10
Leave a Reply