Tell us what’s happening:
Describe your issue in detail here.
Hi I already know the solution to this but don’t understand whats going on.
I don’t understand what we’re doing the sum of and what the “n” element stands for.
I thought it was just the sum of the first to numbers in the array. Your code so far
[spoiler]
function sum(arr, n) {
// Only change code below this line
if (n >= 0) {
//return the 1st value in the array
return arr[0];
} else {
return sum(arr, n-1) + arr[n];
}
// Only change code above this line
}
[/spoiler] Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Replace Loops using Recursion
I’m using plain English, not pseudocode when I describe the behaviour.
That is sum none means return 0
sum 1 means return the first number (at index 0)
sum 2 means return the sum of the first and second numbers (at index 0 and 1)
etc
The reason you don’t need to set arr to anything is because it is a parameter for your function.
The calling code will pass you the array.
no, if the code was working (I am not sure the code you posted does work btw.) the n-1 may be there because it is part of the basis of how recursion works in a working version of this code.
Say, the array provided is 100 numbers long.
And say n is 100, meaning, I want the sum of all the numbers of this array.
How can recursion help us add up 100 numbers or n numbers?
Maybe by saying something like this in plain English:
The sum of a 100 numbers is the sum of the first 99 numbers plus the last number. (the 100th one)
The sum of 99 numbers on the other hand is the sum of the first 98 numbers plus the 99th number.
The sum of 98 numbers?
Well that is the sum of 97 numbers plus the 98th number.
The sum of 97 numbers?
Sum of first 96 plus the 97th number.
etc.
So if you use n-1 it may be for the purpose of reducing the complexity of the problem…
(sum of 100 = sum of 99 + 100th)
(sum of 99 = sum of 98 + 99th)
etc.
Again, I do not believe the code you posted is working code, so I would dump it and start thinking about this one again.