Natural numbers include all positive integers from 1 to infinity. There are multiple methods to find the sum of natural numbers and here, we will see how to find the sum of natural numbers using recursion.
Example
Input : 5
Output : 15
Explanation : 1 + 2 + 3 + 4 + 5 = 15Input : 10
Output : 55
Explanation : 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Approach
- Given a number n,
- To calculate the sum, we will use a recursive function recSum(n).
- BaseCondition: If n<=1 then recSum(n) returns the n.
- Recursive call: return n + recSum(n-1).
Program to find the sum of Natural Numbers using Recursion
Below is the implementation using recursion:
C
// C program to find the sum of n // natural numbers using recursion #include <stdio.h> // Returns the sum of first n // natural numbers int recSum( int n)
{ // Base condition
if (n <= 1)
return n;
// Recursive call
return n + recSum(n - 1);
} // Driver code int main()
{ int n = 10;
printf ( "Sum = %d " , recSum(n));
return 0;
} |
Output
Sum = 55
The complexity of the above method
Time complexity: O(n).
Auxiliary space: O(n).