Tell us what’s happening:
Hi everyone,
I have a couple of questions about the logic and meaning of the recursive function.
I have watched video and read the nice Beau Carnes explanation that worked very well for me because the function he uses takes one single parameter and it’a a number so when the recursive process starts and we are in a hypothetical “return x * fact(x-1);” function It is easy for me to understand that x is a number and the fact(x-1) is a number as well so they can be calculated producing a number.
But in our example we evaluate this function: return multiply(arr, n - 1) * arr[n - 1]; and if arr[n - 1] is clearly a number how do we know what multiply(arr, n - 1) is? Or sum(arr, n-1) ? They should be number as well in order to accept simple operation on them. I can guess that if n is 3 (for example) the (arr - 1) must be 2 in order to satisfy the result but I can not understand why.
Second question is why sum([1], 0) should equal 0. Does not this resolve to an array with negative index?
Hope I made myself clear.
Thank you
L
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];
}
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
.
Challenge: Replace Loops using Recursion
Link to the challenge: