How to sum all integers below a given integer using recursion

Viewed 2029

Right off the bat, this is NOT a homework question. I am practicing recursion problems in my free time and I am still wrapping my head around the concept. I am super close to solving this one, but I can't figure out how to skip the root integer 'n' when I am summing them together. Here is the code so far:

var sumBelow = function (n) {
    console.log(n);
    // base case
    if (n === 0) {
        console.log('we hit the base case');
        return 0;
    }
    // initialize var to hold sum
    if (!sum_sumBelow) var sum_sumBelow = 0;
    // add numbers
    sum_sumBelow = n + sumBelow(n - 1);
    return sum_sumBelow;
};

console.log('answer is', sumBelow(4));

When I call 'sumBelow(4)' what I want is 3+2+1, but I am currently getting 4+3+2+1.

How do I skip the root parameter???

5 Answers
Related