Answers for "sum numbers recursively js"

1

javascript recursive sum function

// Write a recursive method that returns the sum of all elements in an array

function recSum(nums) {
    if (nums.length === 1 ) {
        return nums[0];
    }
    if (nums.length === 0 ) {
        return 0;
    }
    let sum = nums[0] + recSum(nums.slice(1,nums.length));
    return sum;
}
Posted by: Guest on October-24-2020
0

sum numbers recursively js

function sum(n) {
    if (n < 1) return 0;    // exit condition
    return n  + sum(n - 1); // return value plus result of recursive call
}

console.log(sum(3));
Posted by: Guest on March-22-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language