Hi @blkhertzz,
I’m not going to sugarcoat it. There’s quite a bit wrong with your function, as it stands. It’s relying on a multiply
function that doesn’t exist. That multiply function is only talked about in the challenge to give you an example of how that recursion works.
However, since that multiply
function has incredibly similar syntax to how you can program the sum
function, that’s what I’m going to explain so that you can use the very same methodology to create a sum
function.
Each time the multiply
function is ran, it is basically adding to a stack of numbers that are going to do some operation. In the example given of the multiply function, it looks like this really:
(Number at n - 1) * (Number at n - 2) * ... until n == 0 then multiply by 1
The n
value keeps being decremented by 1 every time you call it until n is less than or equal to 0. n
will never be less than 0, though, unless you literally make the initial call to it something like multiply([1,2,3], -2)
.
So, if we take a real example, and say we have the numbers: 2, 3, and 4. And we want to multiply the first 2 together:
multiply([2,3,4], 2)
What ends up being returned is this:
3 * 2 * 1 //Which is evaluated to become the number 6
Why? Because, you called the function initially and said, “Hey, I want n = 2”. It then goes in and says “Okay, well the element there is actually at “n - 1” and that is the number 3 so let’s start to multiply that”. And at the same time, it calls itself again because it’s multiplying the next thing in the list, but this time, n = 1. Well, the number at that location is actually at n - 1, which is 0, and in this specific array is the number 2. It repeats this again putting the number 2 on to the multiplication and then says, “Ok, now n = 0”. Once that happens, the very first if statement executes, because n
is now 0. It returns a 1 back to that initial list, which returns: 3 * 2 * 1 and that is evaluated to become 6.
This same exact concept can be directly applied to the sum
function exchanging any multiplication for addition.
I hope that helps!