🔀⚡Beginner
Calculate Sum of Natural Numbers
Calculate 1+2+3+...+n
Natural numbers are positive integers: 1, 2, 3, 4, ...
Sum of first n natural numbers: 1 + 2 + 3 + ... + n
Method 1: Using Loop
sum_natural_loop.c
C
1#include <stdio.h>23int main() {4 int n, sum = 0;5 6 printf("Enter n: ");7 scanf("%d", &n);8 9 for (int i = 1; i <= n; i++) {10 sum += i; // sum = sum + i11 }12 13 printf("Sum of first %d natural numbers = %d\n", n, sum);14 return 0;15}Output
Enter n: 10
Sum of first 10 natural numbers = 55
Method 2: Using Formula
sum_natural_formula.c
C
1#include <stdio.h>23int main() {4 int n, sum;5 6 printf("Enter n: ");7 scanf("%d", &n);8 9 // Formula: n(n+1)/210 sum = n * (n + 1) / 2;11 12 printf("Sum = %d\n", sum);13 return 0;14}Formula: Sum = n(n+1)/2
For n=10: Sum = 10 × 11 / 2 = 55
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials