C Program to Find Sum of N Natural Numbers
You can find the sum of n natural numbers in C by using a loop or formula; for example,
sum = n * (n + 1) / 2; calculates the sum directly.Examples
Input5
OutputSum of first 5 natural numbers is 15
Input10
OutputSum of first 10 natural numbers is 55
Input1
OutputSum of first 1 natural numbers is 1
How to Think About It
To find the sum of n natural numbers, think of adding all numbers from 1 up to n. You can do this by adding each number one by one or use the formula
n * (n + 1) / 2 which gives the total sum quickly.Algorithm
1
Get input value n from the user2
Calculate sum using the formula sum = n * (n + 1) / 23
Print the sumCode
c
#include <stdio.h> int main() { int n, sum; printf("Enter a positive integer: "); scanf("%d", &n); sum = n * (n + 1) / 2; printf("Sum of first %d natural numbers is %d\n", n, sum); return 0; }
Output
Enter a positive integer: 5
Sum of first 5 natural numbers is 15
Dry Run
Let's trace the input 5 through the code
1
Input
User enters n = 5
2
Calculate sum
sum = 5 * (5 + 1) / 2 = 5 * 6 / 2 = 30 / 2 = 15
3
Output
Prints 'Sum of first 5 natural numbers is 15'
| n | sum |
|---|---|
| 5 | 15 |
Why This Works
Step 1: Input reading
The program reads the number n entered by the user using scanf.
Step 2: Sum calculation
It uses the formula n * (n + 1) / 2 which adds all natural numbers from 1 to n efficiently.
Step 3: Output display
Finally, it prints the calculated sum using printf.
Alternative Approaches
Using a for loop
c
#include <stdio.h> int main() { int n, sum = 0; printf("Enter a positive integer: "); scanf("%d", &n); for (int i = 1; i <= n; i++) { sum += i; } printf("Sum of first %d natural numbers is %d\n", n, sum); return 0; }
This method uses a loop to add numbers one by one, which is easy to understand but slower for large n.
Using recursion
c
#include <stdio.h> int sumNatural(int n) { if (n == 1) return 1; return n + sumNatural(n - 1); } int main() { int n; printf("Enter a positive integer: "); scanf("%d", &n); printf("Sum of first %d natural numbers is %d\n", n, sumNatural(n)); return 0; }
This method uses recursion to add numbers but can cause stack overflow for very large n.
Complexity: O(1) time, O(1) space
Time Complexity
Using the formula calculates the sum in constant time without loops.
Space Complexity
Only a few variables are used, so space is constant.
Which Approach is Fastest?
The formula method is fastest; loop and recursion take O(n) time and more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Formula | O(1) | O(1) | Fastest and simplest |
| Loop | O(n) | O(1) | Easy to understand, good for beginners |
| Recursion | O(n) | O(n) | Demonstrates recursion but less efficient |
Use the formula
n * (n + 1) / 2 for the fastest and simplest solution.Forgetting to use integer division properly or using float variables can cause incorrect results.