Tell us what’s happening:
Describe your issue in detail here.
**Your code so far**
function sum(arr, n) {
// Only change code below this line
let i = 0
let total = 0
if (i > n) {
return;
}
else (i <= n) {
total += arr[i];
i++;
}
// Only change code above this line
}
**Your browser information:**
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36
That’s not a recursion?
A recursion is a function that calls itself, but there is no call to “sum()” within the function.
A recursion is a troublesome thing. You cannot declare variables like that because the funciton calls itself and will re-declare the variables in every call with the innitial value.
That ofcourse is problem number 2, but first you actually need to write a recursive call.
I’d recommend taking the example, working to REALLY understand how it works, maybe grab a video on recursion if you still got trouble - only then try writing your own.
Recursions need a whole new level of thinking, as you now have to keep a recursion-stack of several function calls in mind, to understand what is happening.
Thanks for that response! I had another attempt. Could you help me see why my code didn’t work? And in real life is there only one perfect way to code this problem recursively?
I’ve copy-pasted my second attempt below, followed by the actual correct answer.
/* My second attempt
var i = 0
var total = 0
if (i => n) {
return total;
}
else {
total = sum(arr, n - 1) + arr[n - 1];
}
*/
// Correct answer
function sum(arr, n) {
if(n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
// Only change code above this line
//example call: sum([1,2,3,4], 4)
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
Your code didn’t work in part because you weren’t returning a number in both cases, only in the base case.
And you were also trying to use local variables to keep track of a running total, which won’t work since each time you call the function recursively those variables get reinitialized.