Reputation: 21
This is multiplication function that takes an array and n numbers of elements in the array and returns the multiplication of the N numbers of element in the array.
function multiply(arr, n) {
if (n <= 0)
return 1;
let first = multiply(arr, n - 1);
console.log(`first value: ${first}`);
console.log(typeof(first))
let second = arr[n - 1];
let result = first * second;
return result;
}
const mul = multiply([1,2,3],2);
console.log(mul)
How this recursion replace for or while loop?
Upvotes: 2
Views: 49
Reputation: 36
The function multiply
multiplies the last element of an array with n
elements, i.e. arr[n-1]
with the product of the previous elements of that array.
The "product of the previous elements" is calculated using multiply
itself.
The recursion ends as soon as there are no elements left in the array. Then 1
is taken as the initial factor for the multiplication.
Upvotes: 1