New Topic Of Recursion

Tell us what’s happening:
Hello fellow campers,
I was studying the topic of recursion and i did understand the given example in relation to for loops and i also read the blog post and everything made sense.
But the challenge and the given examples confused me i just didn’t understand where n - 1 came from.
Anyone mind explaining this to me?
Thanks

Your code so far


function sum(arr, n) {
// Only change code below this line
if(n <= 0){
return arr[0]
}
else{
return sum(arr, n-1) * arr[n];
}
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 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

the n-1 is basically to prevent an infinite loop. it would just keep calling sum(arr, n) over and over because n never changes

Hi,

if (n <= 0) {
    return arr[0];
}

In recursive functions this is called the base case. You return something when this meets your base case condition, otherwise you’ll blow your execution stack (the blow out is called stack overflow).
Your second return statement is a recursive function call, so in order to get to the base case, you need to reduce n variable for the reason above.
To better visualise what’s happening, enter your code in this visualiser and step forward.

1 Like

thanks a million buddy