Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of first n natural numbers in C Program
In C programming, finding the sum of the first n natural numbers is a common problem that can be solved using different approaches. The sum of first n natural numbers means adding all positive integers from 1 to n (i.e., 1 + 2 + 3 + ... + n).
For example, if n = 5, then the sum would be: 1 + 2 + 3 + 4 + 5 = 15
Syntax
sum = n * (n + 1) / 2
We have two main methods to calculate this sum −
- Method 1 − Using iterative approach with loops
- Method 2 − Using mathematical formula (more efficient)
Method 1 − Using Iterative Approach
In this method, we use a loop to iterate from 1 to n and add each number to get the total sum −
#include <stdio.h>
int main() {
int n = 10;
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum of first %d natural numbers: %d<br>", n, sum);
return 0;
}
Sum of first 10 natural numbers: 55
Method 2 − Using Mathematical Formula
The mathematical formula for the sum of first n natural numbers is: sum = n * (n + 1) / 2. This approach is more efficient as it calculates the result in constant time −
#include <stdio.h>
int main() {
int n = 10;
int sum = n * (n + 1) / 2;
printf("Sum of first %d natural numbers: %d<br>", n, sum);
return 0;
}
Sum of first 10 natural numbers: 55
Comparison
| Method | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Iterative Approach | O(n) | O(1) | Less Efficient |
| Mathematical Formula | O(1) | O(1) | More Efficient |
Conclusion
The mathematical formula approach is preferred for calculating the sum of first n natural numbers as it provides constant time complexity. For large values of n, this method significantly outperforms the iterative approach.
