I’m gonna point out two things here.
First for the solution to the algorithm, simply look closely at the heart of your function, as “sum” means “the total amount”. This is slightly different than what the explanation code was doing. It’s hard to point you in the right direction here without just giving you the answer.
Secondly, I’d like to try to explain recursion a bit more here by going through how the code would evaluate step by step:
Lets look closely at the core of your sum()
function here:
return sum(arr, n - 1) * arr[n - 1];
What does this do? Lets take an example:
// example function call
sum([2, 3, 4], 1)
If we insert the values, the core code would look something like this:
return sum([2, 3, 4], 1 - 1) * arr[1 - 1];
Lets take this a little further:
return sum([2, 3, 4], 0) * arr[0];
Ok, so now let’s look at what this evaluates to. We know the 0 index of the array arr
is the value 2
return sum([2, 3, 4], 0) * 2;
The function needs to ultimately return a single value, but as you can see above there is still more work this function needs to do before a single value can be returned.
This brings us to the recursive part. Before the function is finished, another function call must be made. It has to call itself before it can get the final value to be returned:
sum([2, 3, 4], 0)
At this point if we were following the code line by line, we would start all over again.
return sum(arr, n - 1) * arr[n - 1];
// insert values
return sum([2, 3, 4], 0 - 1) * arr[0 - 1];
In a different example this can happen over and over until a solution is made. But here, since n
would be 0, we would return 1
because of the base case.
So, ultimately our first function call from above would evaluate to this
return 1 * 2
// or
return 2
By the function calling itself to get the solved value, in some examples calling itself many times, we can recognize it is using recursion.
There are certain programing problems that recursion is a fine solution for.