Tell us what’s happening:
I have gone ahead and looked at the solution but I just can’t get my head around what is happening at the ’ return sum(arr, n - 1) + arr[n - 1];’ section. So for example if: arr = [1,3,4,5] and n = 2, then at the return statement what is actually happening? I can’t work out how the computer is dealing with those numbers if that makes sense? I’ve looked at several guides and videos on recursion and even revisited how functions work but I just can’t understand what is going on ‘behind the scenes’ at the return bit of this particular example. Greatly appreciate any help, thanks.
Right, but sorry that’s my original question. As far as I can see the function never returns a value to work with because it’s always jumping to the ‘else’ block (which then just sends it back to itself with an infinite loop as far as I can tell)…
So we know we will add 3 to the return value of sum([1,3,4,5], 1). So what does sum([1,3,4,5], 1) return? Don’t guess. Don’t tell me what you “think” it returns. It’s a function call to sum just like sum([1,3,4,5], 2) was, so you should be able to tell me exactly what it returns by looking at the definition of sum.
You jumped too far ahead. Just show me the actual code of the return statement for sum([1,3,4,5], 1). Replace all of the variables with their actual values. Just like we did before for sum([1,3,4,5], 2).
Does your answer have everything in that return statment? Look above for what sum([1,3,4,5], 2) returned. You’ve done this before. I’m just asking you to do the same thing again, except this time the second argument is 1 instead of 2.
I know I sound like a broken record, but I feel like you are missing an important concept in recursion and I am trying to make you realize what it is.
Again, look at the actual return statement for the function in the else block (I pasted it again in my previous post). So if we called the function as sum([1,3,4,5], 1) what is that return statement going to be? All you have to do is replace the variables in the return statement with their actual values based on the values passed into the function when we call it with sum([1,3,4,5], 1).
There is no need to be guessing here. You have already done this with the original function call of sum([1,3,4,5], 2). Do you remember that? I asked you up above to replace the variables in the return statement with their values and you did that. If you don’t remember then scroll above to find it. Perhaps that will help you answer the question of what sum([1,3,4,5], 1) returns? Although you really shouldn’t need to look above because you have the code for the return statement and you just need to replace the variables.
return sum(arr, n - 1) + arr[n - 1];
If we call the function as sum([1,3,4,5], 1) then inside the function, what does arr equal? What does n equal? If you know that then you can replace the variables with their actual values and you can tell me what it returns.