VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-to-find-sum-of-natural-numbers-using-recursion/

⇱ C Program to Find Sum of Natural Numbers using Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program to Find Sum of Natural Numbers using Recursion

Last Updated : 8 Jun, 2023

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:


Output
Sum = 55 

The complexity of the above method

Time complexity: O(n).

Auxiliary space: O(n).

Comment
Article Tags: