C program to find the sum of n natural numbers using the formula and a for loop.
First n natural numbers are 1, 2, 3, ...,n. The numbers form an arithmetic progression (AP) with one as the first term as well as the common difference.
Sum of first n natural numbers = n*(n+1)/2.
C program to find sum of n natural numbers
int main()
{
int n, sum;
printf("Enter a number\n");
scanf("%d", &n);
sum = n*(n+1)/2;
printf("Sum of %d natural numbers = %d\n", n, sum);
return 0;
}
Output:
Sum of n natural numbers in C using a for loop
int main()
{
int n, c, sum = 0;
printf("Enter a number\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
sum = sum + c;
printf("Sum = %d\n", sum);
return 0;
}
This method is inefficient because it uses a loop that executes n times (time complexity: O(n)). Use the first method, which uses the formula (time complexity: O(1)) to calculate the sum of first n natural numbers.