Tell us what’s happening:
Describe your issue in detail here.
I don’t understand what’s going on with the array
In every case
Can you step by step to get an answer?
**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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36
If you don’t understand then I have to ask how you came up with the correct answer?
The easiest way to see what is going on here is to write it out on paper. Take the example:
sum([1,2,3], 3)
Using your code, write out what happens each time you call the function. I’ll get you started. The first time you call it you will have:
arr=[1,2,3] and n=3
Since n is greater than 0 you’ll hit the else which will give you:
return sum([1,2,3], 2) + 3
So we are going to return the value 3 plus whatever value is returned from sum([1,2,3], 2). So now you have to figure out what value is returned from sum([1,2,3], 2). And you keep going like this until you hit the base case.
You’ll notice that we did not change the array in any way. We just used it to retrieve a value and then we passed it into sum again so we can use it to retrieve a value if we hit the else again.
I’m not sure I understand what you are asking here? The requirements for the function sum are that it sum the first n elements in the array. So that’s the answer that the function produces.
In this case, we returned sum([1,2,3], 2) not one number as in the example
sum([2, 3, 4], 1) this number 2
sum([2, 3, 4, 5], 3) this number 9
As a result, we get 2 and 9?
in this example sum([1,2,3], 2) we get 2? or 1+2+3+2=8? or 6?
In my example, the first time we called sum([1,2,3], 2) we returned sum([1,2,3], 2)plus the value 3:
return sum([1,2,3], 2) + 3
So we are returning a number, we just don’t know what that number is yet because we still have to resolve sum([1,2,3], 2). (We do know that the number will be at least 3).
This is how recursion works, it keeps calling itself and gradually builds the final answer by adding all the recursive answers together.
So continue the process. What does sum([1,2,3], 2) return? You are going to add that to 3. It is either going to return 0 (if it hits the base case) or it is going to return a number plus another recursive call.
sum([1,2,3], 2)
sum([1,2,3],2-1)+arr[2-1]
sum([1,2,3],1)+arr[1] = sum([1,2,3],1)+2
sum([1,2,3],1-1)+arr[1-1]+2=sum([1,2,3],0)+arr[0]+2=sum([1,2,3],0)+1+2=0+1+2=3
Answer 3
Thank you so much! Now I understand…