Recursive n == 0 vs n<= 0

*Tell us what’s happening:
I originally wrote if(n == 0) and this worked.
However, the standard answer would be n<= 0
Would you say both answers are correct?
Your code so far
function sum(arr, n) {
// Only change code below this line
if (n == 0 ) {
return 0;
} else {
return sum(arr, n-1) + arr [n-1];
// until reaching 0
}
// Only change code above this line
}


function sum(arr, n) {
 // Only change code below this line
if (n <= 0 ) {
return 0;
} else {
return sum(arr, n-1) + arr [n-1];
// until reaching 0 
}
 // Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.

Challenge: Replace Loops using Recursion

Link to the challenge:

If you use n < 1, you have no chance of an infinite loop from a stupid user (possibly future you).

1 Like

In “counting down” recursion (pretty common technique), I’ve seen both n == 0 and n <= 0 for the base case out in the wild. I prefer the latter on mathematical grounds, since even if you strictly check that n is positive at the very start, you still want your functions to be total – you want to be able to throw any value (that typechecks) at them and get some kind of defined and expected output. Crashing with a stack overflow isn’t well-defined output.

It hardly matters for this one case, but sticking with total functions where you can becomes really useful once you start composing dozens of functions together in a program.

1 Like