Hello,
I have read other posts and watched various videos but am still stumped on comprehending the example code in this exercise.
-
I understand the concept of recursion being a “reflection,” calling itself as a sort of “shortcut” from using loops in order to execute statements until you reach the desired result.
-
I understand that a “base case” acts as your insurance against infinite loops, and the “recursive case” is your continuous, loop-like code.
-
I understand that there are no real advantages or disadvantages to either (aside from memory usage), that loops are preferred (or so I read), and that this concept of recursion will be important for algorithms later on. I want to get this down.
My issue is with understanding the logic of the example code.
//I understand this completely:
function multiply(arr, n) {
var product = 1;
for (var i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}
//I cannot wrap my head around:
//However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]. That means you can rewrite multiply in terms of itself and never need to use a loop.
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
Specifically:
notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]
How did they make that equivalency? And are they using both the original multiply function in addition to this newer recursive function? How does this latest function execute any actual statements without the older function example?
Thank you for any assistance.
Challenge: Replace Loops using Recursion
Link to the challenge: