why does ‘return 1’ do this? i thought that would literally return 1 as a result, rather than the multiplication result.
(i also wrote a summing function which only works with return 0.
not understanding the return command here)
function multiply(arr, n) {
if (n <= 0) {
return 1;
} else {
return multiply(arr, n - 1) * arr[n - 1];
}
}
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36
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.
this returns the func value + whatever the IF statement is told to return (0 therefore works, but why would it return [ELSE func + return ‘x’ of IF] statement?)
Why would it be wrong? I don’t see a reason for it to be wrong. The product of n = 0 elements should be equal to 1.
Not quite. The return statement
return sum(arr, n-1) + arr[n-1];
adds together the result of calling the function with the argument n - 1 (which represents taking the sum of the first n - 1 elements in the array) and the nth element of the array (at index n - 1).