0

Summing numbers between one and a given number without recursion is simple:

function sumNums (num) {
  let array = [];
  for (let i = 0; i <= num; i++) {
    array.push(i);
  }
  return array.reduce((a, b) => a + b);
}
console.log(sumNums(3)); 

6

But what I don't understand, is that when we're using recursion, it causes the "loop" to occur throughout the entire function.

So if we have a for-loop (or any loop) within a function that's using recursion, it will cause an error - right?

And I assume that we'll need an array of the integers in order to reduce them - So know how else can we create an array of integers between one and and a given number without using some sort of loop?

EDIT: A simpler way of adding integers between 1 and num without recursion:

function sumNums (num) {
  let sum = 0;
  for (let i = 1; i <= num; i++) {
    sum += i;
  }
  return sum;
}
console.log(sumNums(3)); 

No need to add the integers to an array and then reduce it. Just add them to an initializer variable instead.

HappyHands31
  • 4,001
  • 17
  • 59
  • 109
  • 2
    Please post the code of the recursive function that you keep talking about. – Bergi Jun 21 '19 at 17:52
  • 1
    Why are you creating an array at all? You could just add up the numbers directly. – melpomene Jun 21 '19 at 17:52
  • 3
    Using a loop in a recursive function does not cause an error. Why would it? – melpomene Jun 21 '19 at 17:52
  • 1
    Is each number is incremented by 1 from starting number to given number? – Vikas Keskar Jun 21 '19 at 17:53
  • 2
    The key is that if you use recursion, you don't need a loop. You just pass in (current value + 1) to the next call of the function. – IceMetalPunk Jun 21 '19 at 17:53
  • 4
    I don't see any recursion here -_- – Code Maniac Jun 21 '19 at 17:53
  • 1
    I hate tasks, that force people to use an unfit method. There are plenty examples, where recursion makes sense. Here, it doesn't. – ASDFGerte Jun 21 '19 at 17:53
  • @VikasKeskar Yes – HappyHands31 Jun 21 '19 at 17:53
  • 1
    @CodeManiac That's why the question says *without recursion* before the code. – melpomene Jun 21 '19 at 17:53
  • @ASDFGerte - that's why this smells of "professor" driven task vs. "I have to get this work done" task. – Randy Casburn Jun 21 '19 at 17:54
  • The sum of the numbers between 1 and n is n + the sum of the numbers between 1 and n-1. – Pointy Jun 21 '19 at 17:55
  • Also the closed-form formula `n * (n + 1) / 2` is the correct way to compute the result. – Pointy Jun 21 '19 at 17:55
  • Why do you need an array at all? – Pointy Jun 21 '19 at 17:56
  • Re all comments above, the OP seems to be asking for "how to" not "should I" or "is there a better alternative". These comments are mostly irrelevant. – junvar Jun 21 '19 at 17:57
  • 1
    If want to directly calculate sum, then refer this https://math.stackexchange.com/a/1842203 – Vikas Keskar Jun 21 '19 at 17:58
  • Here using recursion is not a wise choice, you should use iteration method as long as it is possible with iteration. – Code Maniac Jun 21 '19 at 17:58
  • Perhaps this is _most_ relevant comment: OP, please read this: https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions – Randy Casburn Jun 21 '19 at 17:59
  • 1
    you have your answer, but here another version where tail call optimization can occur: `function sum(num, total=0){ return num > 0 ? sum(num-1, total+num) : total; }` – Thomas Jun 21 '19 at 19:13
  • @Thomas thanks, can you please create an answer below? – HappyHands31 Jun 21 '19 at 19:42
  • @HappyHands31 while you question is closed as duplicate it is not possible to add a new answer – bruno Jun 21 '19 at 19:48
  • @HappyHands31 I think tco is beyond the topic for this question. This comment was meant more like a teaser, and a direction, for you to dive deeper into recursions. I'd find it great if you would end up understanding why and how my function can be optimized by the engine in a way that the ones in the answers can't. – Thomas Jun 21 '19 at 19:55
  • @bruno I see. Well, this question should not be a duplicate. The articles that are listed for where answers already exist for this question, are different from mine. [This article](https://stackoverflow.com/questions/37425581/sum-of-an-array-using-recursion-javascript) talks about summing an array, where an array is passed in as an argument. And [this article](https://stackoverflow.com/questions/29549836/how-to-find-the-sum-of-all-numbers-between-1-and-n-using-javascript) talks about summing all integers between 1 and N, but it does not mention using recursion. – HappyHands31 Jun 21 '19 at 20:10
  • There is plenty of talk here about how I'm not showing any attempts at recursion in my initial code, but, since I'm trying to learn recursion, my attempt was so bad that I felt as though it wasn't even worth showing. Part of the issue here is that there's an easier way to sum all integers between 1 and N without using an array. And I have shown that in the edit. – HappyHands31 Jun 21 '19 at 20:15

2 Answers2

4

You could check the value and if truthy return n plus the sum of n - 1.

function sum(n) {
    return n && n  + sum(n - 1);
}

console.log(sum(3));

A more traditional approach take the handed over value and checks if the value is smaller than one and returns zero in this case, otherwise the result of the actual value plus the result of calling sum function with a decrement value.

function sum(n) {
    if (n < 1) return 0;    // exit condition
    return n  + sum(n - 1); // return value plus result of recursive call
}

console.log(sum(3));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    Why would this get a downvote? It's a working solution. – Pointy Jun 21 '19 at 17:57
  • 1
    @Pointy probably because the base case is unnecessarily obfuscated. "truthy" is not what matters. – Bergi Jun 21 '19 at 18:00
  • It has nothing to do with the question. – melpomene Jun 21 '19 at 18:09
  • I wasn't the one to downvote, but I don't understand why it works. As @Bergi pointed out, there doesn't seem to be a traditional base case here (if-statement)? I'm just trying to learn the basics of recursion. – HappyHands31 Jun 21 '19 at 18:10
  • So `return n + sum(n - 1)` ....If `n` is 3.....then we have `return 3 + sum(3 - 1)`, which equals `return 3 + sum(2)` So 5. Then `return 5 + sum(5 - 1)`, which equals `return 5 + sum(4)`, which equals 9....so I still don't really understand. How is that getting closer to the base case? – HappyHands31 Jun 21 '19 at 18:42
  • 1
    the first is `3 + sum(2)`, the second is `3` from first part and `2 + sum(1)` from the second call and the final one is `1 + sum(0)` which is `1`, then a the call before is `2 + 1` the the result before is `3 + 3`. – Nina Scholz Jun 21 '19 at 18:46
0

let sumNumsRecursive = num => num ? sumNumsRecursive(num - 1) + num : 0

console.log(sumNumsRecursive(3)); 
junvar
  • 11,151
  • 2
  • 30
  • 46