Replace Loops using Recursion , its looking difficult to me ,, anyone can explain it to me?

Tell us what’s happening:

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0.

Challenge: Replace Loops using Recursion

Link to the challenge:


I think this video explains recursion really well!

Basically, you use the formula in else to break down the formula until it reaches the lowest point where the formula cannot be broken down again.

Sum([2,3, 4, 5], 3])

-> means
sum([2, 3], 2) + arr[2] ;
sum([2], 1) + arr[1] + arr{2};
arr[0] + arr[1] + arr[2];
2 + 3 + 4
9

1 Like

Hi!

You have a typo in your code:
Your recursion should return 0 and NOT 1 in the case of n smaller or equal to zero!