Can someone help me understand recursion?

not exactly

that line you have sum(arr, 3) + arr[4]

so sum(arr, 3) returns 10, arr[4] is 5, you get 10+5 = 15

1 Like

Im getting confused at sum(arr, n -1) + arr[n];
just to be clear

( arr, n - 1 ) is ( [1,2,3,4,5], 4) right? so when the function calls itself the (, 4 is reducing itself to 3 , 2 , 1 , 0 ) right?

if the above it correct what is + arr[n] doing?

you write the function call sum([1,2,3,4,5], 3)

inside that function there is the line

   return sum(arr, n-1) + arr[n]

which putting in the values is

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

by definition sum([1,2,3,4,5], 2) returns the sum of the elements from index 0 to index 2, so it is 1+2+3=6 - so it returns 6
and arr[3] has value of 4

so it becomes

   return 6 + 4

so the function sum([1,2,3,4,5], 3) returns 10 which is the sum of the numbers in the array from index 0 to index 3

1 Like

Thanks for the explanation i think i understood it (almost)

I have some doubts still…

return sum(arr, n-1) + arr[n]
which is
sum([1,2,3,4,5], 4) + arr[4] by default right? But because of n-1
the first loop itself will be n3 `sum([1,2,3,4,5], 3) + arr[4]

So it’s adding 1+2 = 3 + 3 = 6 + 4 = 10 (right?) and then because we have + arr[4] which is 5 in the array it will add the 5 from the array to the last answer which is 10 so in total its 15?

no, n-1 doesn’t equal n so if arr[n] is arr[4], sum(arr, n-1) will be sum(arr, 3), not sum(arr, 4)

this is correct

1 Like

Because of the - 1 it’s removing 1 from the 4 right? So its 3?

hi bro I need help on javascript pls

If you have a question, please post a separate topic and ask it there. Thanks.

If you do that as per your explanation, it doesn’t give you the same thing when it is run in the console.

my explanation was for a different version of the challenge, with current version it would be like this:

let arr = [2,3,4,5,6,7,8]
multiply(arr, 3); // this is equal 2*3*4
multiply(arr, 2); // this is equal 2*3
// so you can say that line 2 is equal to below:
multiply(arr,2) * arr[2]; // this is equal (2*3) * 4