C Program to Find Sum of Natural Numbers using Recursion
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 = 15
Input : 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
#include <stdio.h>
int recSum( int n)
{
if (n <= 1)
return n;
return n + recSum(n - 1);
}
int main()
{
int n = 10;
printf ( "Sum = %d " , recSum(n));
return 0;
}
|
The complexity of the above method
Time complexity: O(n).
Auxiliary space: O(n).
Last Updated :
08 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...