Basic JavaScript - Replace Loops using Recursion , Why n - 1?

But we said

sum([2, 3, 4, 5], 1) will return sum([2, 3, 4, 5], 0) + 2

That’s definitely not 9

I must need to review some past excersises and go through them again, I really did not have much difficulty until this exercise. Thanks for taking the time, if you think of any topics specifically I should go over , I would like to review them.

I think I understand now, sum( arr, n-1) is asking me for the “n-1” ELEMENTS of the array so in this case (arr, 3-1) == the first 2 elements 2 and 3 and then adding them to the arr[ 3 - 1 ] ==arr [2] with 4 being at index 2 in the array. That works out to sum(2 + 3) + arr[2] (4) == 9.

Sorry, but your logic isn’t correct :slightly_frowning_face:

Go back to the second to last post by @JeremyLT:

sum([2, 3, 4, 5], 3) will return sum([2, 3, 4, 5], 2) + 4

sum([2, 3, 4, 5], 2) will return sum([2, 3, 4, 5], 1) + 3

sum([2, 3, 4, 5], 1) will return sum([2, 3, 4, 5], 0) + 2

and sum([2, 3, 4, 5], 0) will return 0

This is all of the function calls that are made during the recursion, until finally they reach the base case. You are basically working your way down the recursion to the base case. Now you have to work your way back up.

sum([2, 3, 4, 5], 1) will return sum([2, 3, 4, 5], 0) + 2
sum([2, 3, 4, 5], 0) will return 0

Do you see how you can replace sum([2, 3, 4, 5], 0) with 0 in the first line? So sum([2, 3, 4, 5], 0) + 2 is equal to 0 + 2, and thus sum([2, 3, 4, 5], 1) will return 2. Now you can go up to the next line:

sum([2, 3, 4, 5], 2) will return sum([2, 3, 4, 5], 1) + 3

Now that we know sum([2, 3, 4, 5], 1) returns 2 we can replace it in this line. So sum([2, 3, 4, 5], 2) returns 2 + 3, or 5. Now we can go up one more line to the original return statement:

sum([2, 3, 4, 5], 3) will return sum([2, 3, 4, 5], 2) + 4

And we know now that sum([2, 3, 4, 5], 2) returns 5 so we can replace it, and thus sum([2, 3, 4, 5], 3) returns 5 + 4 or 9.

Keep in mind that each recursive call is like calling a completely different function. What if I gave you the following functions:

function a() {
  return b() + 15;
}

function b() {
  return c() + 24;
}

function c() {
  return d() + 33;
}

function d() {
  return 0;
}

Would you have any trouble telling me what the function a returns? Could you explain to me how the value for a is calculated? Recursion works the same way.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.