Unlocking the Power of Recursion: A JavaScript Exploration

The Natural Numbers Enigma

The world of mathematics is full of fascinating concepts, and natural numbers are one of them. These positive integers, starting from 1, 2, 3, and so on, have intrigued mathematicians for centuries. But what happens when we try to calculate their sum using JavaScript? Let’s dive into the realm of recursion and find out.

The Recursive Approach

In our example, we’ll create a sum function that takes a user-inputted number as a parameter. This function will call itself repeatedly, decreasing the input number by 1 until it reaches 0. But what’s the magic behind this process?

How it Works

When the user enters a number, the sum function springs into action. If the input number is greater than 0, the function recursively calls itself with the decremented value. This cycle continues until the number reaches 1, at which point the program halts. However, if the user enters a negative number, the function returns the input value and terminates.

The Code Behind the Magic

Here’s the JavaScript code that brings this concept to life:
“`
function sum(n) {
if (n > 0) {
return n + sum(n – 1);
} else {
return n;
}
}

let num = parseInt(prompt(“Enter a number: “));
console.log(sum(num));
“`
The Result

Run the code, and you’ll see the sum of natural numbers up to the inputted value. For instance, if you enter 5, the output will be 15 (1 + 2 + 3 + 4 + 5).

Further Exploration

Want to explore more JavaScript programs that manipulate natural numbers? Check out our article on finding the sum of natural numbers using different approaches. The world of JavaScript is full of surprises – stay curious and keep coding!

Leave a Reply

Your email address will not be published. Required fields are marked *