Sum of Natural Numbers Using Loop
#include <stdio.h>
int main() {
int N, i;
int sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &N);
for (i = 1; i <= N; i++) {
sum += i;
}
printf("Sum = %d\n", sum);
return 0;
}
Enter a positive integer: 5
Sum = 15
This method iterates from 1 up to the user-specified limit and adds each number to an accumulator variable. The result is printed after the loop completes.
Sum of Natural Numbers Using Formula
#include <stdio.h>
int main() {
int N;
int sum;
printf("Enter a positive integer: ");
scanf("%d", &N);
sum = N * (N + 1) / 2;
printf("Sum = %d\n", sum);
return 0;
}
Enter a positive integer: 10
Sum = 55
The formula N × (N + 1) / 2 provides a constant-time way to compute the sum of the first N natural numbers without iteration. This is especially useful for large values of N.
