# Need clarification

Tell us what’s happening:
“multiply(arr, n) == multiply(arr, n - 1) * arr[n]” makes no sense to me according to the exercise. Trying to wrap my head around it but i just dont understand it at all. Can someone explain this to me? Thanks.

``````
function sum(arr, n) {
// Only change code below this line

// Only change code above this line
}

``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36`.

Challenge: Replace Loops using Recursion

`multiply(arr, n)` by definition will return the multiplication of all elements in the array from `arr` to `arr[n]`
so: `arr * arr * ... * arr[n-1] * arr[n]`

`multiply(arr, n-1)` will return the multiplication of the elements in the array from `arr` to `arr[n-1]`
so: `arr * arr * ... * arr[n-2] * arr[n-1]`
if you multiply this last by `arr[n]` it gives the same value of above
so `multiply(arr, n-1) * arr[n] === multiply(arr, n)`

1 Like

Consider the following array for the value of `arr` and value for `n`:

``````let arr = [1, 2, 3, 4, 5]
let n = 4;
``````

In simple terms, calling `multiply(arr, n)` on the above array should return the result of multiplying all the above elements (recall that array indices start at 0, so elements 0 through 4, rather than 1-5). i.e. 1*2*3*4*5 = 120.

Now if we consider `multiply(arr, n-1)`, in other words `multiply(arr, 3)`, we’d get the results of only the first 4 numbers, so 1*2*3*4 = 24. Multiplying that result with `arr[n]`, which in this case `arr[n] -> 5`, we get 24 * 5 = 120.

Recursion is the idea of breaking a larger problem down into simpler, repeated problems of itself. Rather than saying “find the product of all 5 numbers”, we say “multiply everything before the last item and find the product of that with the last item”.

How do we multiply everything before the last item? Well that’s just another array of numbers with one less item. Repeat over and over and you break it down into finding the product of the first two numbers. Here’s a more visual explanation. Let’s use parentheses to show things we haven’t calculated:

``````(a) 1 * 2 * 3 * 4 * 5 = (1 * 2 * 3 * 4) * 5
|-------------|
How do we calculate this? Use result from (b)

(b) 1 * 2 * 3 * 4 = (1 * 2 * 3) * 4
|---------|
Use result from (c)

(c) 1 * 2 * 3 = (1 * 2) * 3
|-----|
Use result from (d)

(d) 1 * 2 = (1) * 2
|-|
Use result from (e)

(e) 1 => 1
according to first if statement of the example, n = 0 so we return the actual value of 1 here
``````
1 Like

you explained it well sir! i fully understand now