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
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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.
I just assumed because the example does this I may as well stick to the same method of writing the code for continuity, also from my understanding the case is just used to stop the recursion from looping infinitely so I thought the base case I wrote was just if I get a value that is less than 0 then the function should just return 1, was that the wrong thing to do ?
function sum(arr, n) {
// Only change code below this line
console.log("n:" + n);
console.log("arr: [" + arr + "]");
if (n < 0) {
return 1;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
// Only change code above this line
}
console.log(sum([2, 2], 0)); // Should be 0
What do you see?
Before I can easily explain the issue with return 1, we have another problem to find.
should the if statement be less than or equal to zero ?
ps do the initial console. Logs help with anything apart from visualizing what’s going on with the code?
so I implemented console.log ( console.log(sum([1,2],2)) ) into the code and called the function, but I got 4 so I think for some reason my function is adding the 1 index to its self, which is weird because it should be doing the same thing as the example code so now I’m actually confused , I get that recursion in its simplest form is a function calling itself and I thought my solution made some sort of sense, also my solution is the same as the example code however its addition instead of multiplication
also as to why less than or equal to zero, I assume its because we have a possibility of getting 0 as an n value so I wanted to account for that possibility but dismiss any values below zero.
I don’t understand how either the example code or my code works, though I did,I thought that was the right thing to do as it allows values of zero to be used as n and values less than zero to be the stopping criteria, don’t know how the problem works
right so went to have food and changed the condition and it worked, genuinely was insanely simple, thank you very much for the guidance. Also understood why I couldn’t use the same base case for multiply as i did for the sum.