Tell us what’s happening:
Forgive me for my dumbness, I am still a bit confused at the recursive part of this problem. Can someone check my logic in understand why we do this? -->
return sum(arr, n - 1) + arr[n - 1];
I understand, that (arr, n-1) essentially is finding the nth element in the array by finding the index number. So if the example number is 3, it is locating what the index version is, (2)?
ex: sum([2, 3, 4, 5], 3)
arr[2]
And then it is adding to that, arr[2-1].
Why subtract one? Is it to get to the previous indexed number? But if so, we so far have 4 + 3, and now we loop back.
But how does it add up the sum total from ALL the previous attempts and without just repeating the same exact index values? I am very confused on this logic and why it is the way it is done. Can someone please make sure I am understanding correctly? I did not provide my code because I only go the base correct.
I watched a recursive countdown video by Colt and it made total sense as a beginner, this problem seems more difficult, I am surprised we cannot do this without a type of loop. #ignorance
function sum(arr, n) {
if(n <= 0) {
return 0;
} else {
return sum(arr, n - 1) ;
}
}
#### Code Explanation
The `if` statement checks to see if `sum` is evaluating the base case, `n <= 0` , or not. If it is, then `sum` returns the answer, `0` - the sum of elements from 0 to 0 inclusive. Otherwise, it recurses by evaluating a simpler function call, `sum(arr, n - 1)` . Once that returns it adds a single array element, `arr[n - 1]` , to it and returns that sum.
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36
Challenge: Replace Loops using Recursion
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion sum([2, 3, 4, 5], 3)
should equal 9.