Why do I return 0 instead of 1 like in the example code?

Tell us what’s happening:
Describe your issue in detail here.

I am struggling to understand why I am returning 0 instead of 1 or vice versa?

  **Your code so far**

function sum(arr, n) {
if(n <= 0) {
  return 0;
} else {
  return sum(arr, n - 1) + arr[n-1]

Challenge: Replace Loops using Recursion

Link to the challenge:

If you are starting a sum (adding numbers) and you need a starting number that will not affect the final output, then you want 0 - adding 0 to anything does not affect the final sum. That is our initialization.

If you are doing a product (multiplying) then 1 is the number that won’t affect the final product. That is our initialization.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.