JavaScript(JS) JS find sum of natural numbers using recursion
https://.wwwtheitroad.com
To find the sum of the first n
natural numbers using recursion in JavaScript, you can use the following code:
function sum(n) { if (n <= 1) { return n; } else { return n + sum(n - 1); } } // Example usage console.log(sum(5)); // Output: 15
In this example, the sum
function takes a single argument n
, which represents the number of natural numbers to add together. If n
is less than or equal to 1, the function returns n
(which represents the sum of the numbers). If n
is greater than 1, the function returns n
plus the sum of the first n - 1
natural numbers (which is calculated recursively by calling the sum
function with an argument of n - 1
). This process continues until the base case is reached (when n
is 1 or less), at which point the final sum is returned.