Open In App

C Program to Find Sum of Natural Numbers using Recursion

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Sum of first N natural numbers

 

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




// 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).


Last Updated : 08 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads