PUBLISHED ON: JANUARY 19, 2023
JavaScript Program to find Sum of Natural Numbers Using Recursion
We will use recursion in this JavaScript program to find the sum of natural numbers. Recursion is a programming technique in which a function, either directly or indirectly, calls itself. It can be a useful tool for problem-solving, especially when the problem can be divided into smaller problems that are similar to the original problem. In this case, we'll use recursion to calculate the sum of natural numbers by adding the current number to the sum of the numbers that came before it.
This program is an excellent example of how to use recursion in practice to solve a common problem in an efficient and elegant manner. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Approach
The user is asked to enter the number to which he wants to find the sum.
Then the sum() function is called by passing the parameter that the user entered.
- If the number is greater than 0, then the function calls itself by decreasing the value of the number by 1.
- This process continues until the number is equal to 1, and when the number reaches 0, the program stops and returns the number itself (ie. 0).
- If the user enters a negative number, the negative number gets returned by the recursion function and the program stops.
Program to find Sum of Natural Numbers Using Recursion
// JavaScript program to find the sum of natural numbers using recursion
function Sum(num) {
if(num > 0)
return num + Sum(num - 1);
else
return num;
}
const num = parseInt(prompt('Enter an integer: '));
var result = Sum(num);
console.log("The sum is ", result);
Enter an integer: 6
The sum is 21
Conclusion
Finally, this JavaScript program shows how to use recursion to find the sum of natural numbers. This program is an excellent example of how recursion can be used to solve common problems in practice.
Furthermore, this program can be easily modified to find the sum of natural numbers up to any given limit, making it a versatile tool for future problems. Overall, the program's use of recursion effectively simplifies the problem, making it simple to understand and implement.