-1

I don't have much practice with recursion and I have only some experience with javascript.

How do I refactor the code below to use recursion instead of the for loop?

 function add(a, b) {
    var sum = 0;    
    for (var i = a; i <= b; i++) {
            sum += i;
        }
        return sum;
    }
    
   console.log(add(3,7)); //25

The for loop makes sense to me; recursion not so much.

Josh Adams
  • 2,113
  • 2
  • 13
  • 25
cocomatt
  • 131
  • 1
  • 2
  • 11

2 Answers2

1

You could use another parameter for the sum of the last call, for a later tail call optimisation of the recursive call.

At start, initialize s which keeps the summed result and add a.

The perform an exit check, if the target value is reached, then exith with the sum s.

Otherwise call the function again with reduced start value, given end value and the actual sum of all.

Don't forget to return the value of the call.

function sum(a, b, s) {
    s = s || 0;
    s += a;
    if (a === b) {
        return s;
    }
    return sum(a + 1, b, s);
}

console.log(sum(3, 7));

Without tail optimization, this keeps all intermediate results in stack.

function sum(a, b) {
    if (a === b) {
        return a;
    }
    return a + sum(a + 1, b);
}

console.log(sum(3, 7));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

EASY WAY:

function recursive(a, b)
{
  if(a > b)
  {
    return 0;
  }
  return a + recursive(a+1, b);
}

console.log(recursive(3,7));

HARD WAY: (EASY + EXPLANATION)

What is a recursion in a common programming language?

according to Wikipedia: Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration).

translated in everyday language a recursion is when you iterate n-times a function(in this case) and every time that the function call hisself wait for the result of the invoked function's instance.

The invoked functions's intance will invoke himself another time and wait for the result.

When this endless loop will stop?

When an instance will finally return a value, this happens typically with a check before the recursive call(see the easy way).

When a function will return a value all the knots will be loose and the first function that started the cycle will return the final value.

if you want to go deep or just my short explanation was not convincing i reccoment you to read this article: https://www.codecademy.com/en/forum_questions/5060c73fcfadd700020c8e54

Davide Gozzi
  • 121
  • 5