Replace Loops using Recursion - CryptoValues

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

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:

1 Like

sum([1], 0) reaches the base case n <= 0 where 0 is returned.

Actually to get result from any other function calls - like sum(arr, n-1) recursive function also needs to be able to reach that base case.

How do we know what sum(arr, n) is? We don’t, this is the tricky part to fully understand.
When sum(arr, n) is first called the value of it is unknown, but we know that to get value of sum(arr, n) we need to calculate:
sum(arr, n - 1) + arr[n - 1]
We know what arr[n - 1] is. That’s kind of clear, but now we need to figure out what value sum(arr, n - 1) has. How to do that? Again we use the recursive call, but with n smaller by 1:
sum(arr, n - 2) + arr[n - 2]
Again we know what arr[n - 2] is, but sum(arr, n - 2) is still unknown.

This goes on and on, until that base case is reached. At that point we got both of
sum(arr, 0) + arr[0] -> 0 + arr[0] can this value take to the call of the sum(arr, 1) and further up until the original function call.

That’s useful, thank you