We are given a number N and the task is to find the sum of the first n natural numbers using recursion.
Approach to Find Sum of Natural Numbers using Recursion:
In this approach, we are using the function to get the sum of the first N natural numbers.
First, we declare a function findSum(n) and pass the number (n) till now sum is calculated. Then check if the number is not equal to zero then return the n + findSum(n-1) otherwise return the number n (the number n is the sum of natural numbers).
Example 1: In this example, we will calculate the sum of the first 5 natural numbers.
Javascript
// Javascript program to find the sum of // first n natural numbers function findSum(n) { if (n !== 0) return n + findSum(n - 1); else return n; } // Driver code const n = 5; console.log(findSum(n)); |
15
Example 2: In this example, we will calculate and output the sum of the first 10 natural numbers.
Javascript
// Javascript program to find the sum of // first n natural numbers function findSum(n) { if (n !== 0) return n + findSum(n - 1); else return n; } // Driver code const n = 10; console.log(findSum(n)); |
55