Replacing loops with recursion 2

 function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1]; // I can not understand this line, tell me please?
    }
  }

What about that line is confusing you?

return multiply(arr, n - 1) * arr[n - 1];

This line is saying that the function returns the result of multiply(arr, n - 1) (i.e. the product of the first n - 1 entries in the array) multiplied by arr[n - 1] (i.e. the nth entry in the array).

Please let me know if I can explain better.

1 Like

(arr, n - 1) * arr[n - 1]; Can’t figure out how it multiplies here with each other? Thanks for the help!

You aren’t multiplying (arr, n - 1) * arr[n - 1].

You are multiplying multiply(arr, n - 1) * arr[n - 1].

If parentheses make it clearer:

//     (    First Number    ) * (Second Number)
//     (Product of first n-1) * (last number)
return (multiply(arr, n - 1)) * (arr[n - 1]);
1 Like

What I see now is that the expression is returning, but multiplication of the number by an array probably confuses me)) Thank you, I understood a little, you helped me, but if it’s not difficult for you, could you show me the application of this recursion as an example?

It’s multiplication of a number and a number. The multiply() function returns a number, and arr[n - 1] is a single number from the array.

A fun little example of the idea behind recursion is the Fibonacci numbers.

The Fibonacci numbers are a sequence of numbers formed by adding the previous two numbers to make the next number.

fib_0 = 0
fib_1 = 1
fib_2 = 1
fib_3 = 2
fib_4 = 3
fib_5 = 5
fib_6 = 8
fib_7 = 13
fib_8 = 21
fib_9 = 34
fib_10 = 55
...

The formula for Fibonacci numbers is fib_n = fib_(n-1) + fib_(n - 2). That means that you can write a function that makes Fibonacci numbers with recursion (though it’s not the fastest way)

// Brief: generate nth Fibonacci number
// Input:
//   n: which Fibonacci number to generate
// Output:
//   nth Fibonacci number
function fib(n) {
  if (n <= 0) {
    // Base case 0: fib_0 = 0
    return 0;
  } else if (n === 1) {
    // Base case 1: fib_1 = 1
    return 1;
  } else {
    // Recursive definition: fib_n = fib_(n-1) + fib_(n-2)
    return fib(n - 1) + fib(n - 2);
  }
}

// Sample function output
console.log(fib(0));
console.log(fib(1));
console.log(fib(10));
1 Like

Now I understand everything! Thank you very much!

1 Like