Home > Net >  Keep failing practicing recursive functions
Keep failing practicing recursive functions

Time:01-02

I have looked at countless examples and I don't know what I keep doing wrong. I want to make a function that prints a multiplication table of 10 (1x 10 till 10x10), but I keep getting maximum call stack size exceeded errors while similar functions written by others who look just as similar run without issue. Can anyone help me with this. I find recursion really hard to understand.

`

recursionTable = (multiplier) => {
    let num = 1;

    if (num === 10) {
        return "We've hit the end, my friends."
    }
    return (num   1) * recursionTable(multiplier);
}

console.log(recursionTable(10));

`

Expecting a multiplication table of 10 (from 1x10 till 10x10) through recursion, but after looking at examples for hours nothing seems to work even if I mimic those.

CodePudding user response:

You are passing multiplier with no start condition. Below code can solve your problem :

recursionTable = (multiplier, num) => {

    if (num === 10) {
        return "We've hit the end, my friends."
    }
    else {
      console.log(num * multiplier);
    }
    return recursionTable(multiplier, num   1);
}

let num = 1;
console.log(recursionTable(10, num));

CodePudding user response:

The problem with your code is that you make your num = 1 on every recursion, to prevent that you should refactor your code like this:

recursionTable = (multiplier) => {
  if (num === 10) {
    return "We've hit the end, my friends."
  }

  num  = 1;
  return num * recursionTable(multiplier);
}

let num = 1;

Or send 2 values as parameters in your function

recursionTable = (multiplier, initValue) => {}

And replace your internal num value with initValue

CodePudding user response:

try this:

function recursionTable(multiplier) {
  let num = 1;

  if (num === 10) {
    return "We've hit the end, my friends.";
  }

  console.log(`${num} x ${multiplier} = ${num * multiplier}`);

  return recursionTable(multiplier, num   1);
}


console.log(recursionTable(10));

CodePudding user response:

Thanks guys for all the help! I'm starting to get the hang of it. Turned out like some of you pointed I didn't even include the formula for the recursion to do anything. Now that it works and I've read over it, it really starts to make sense. Thanks again!

Code I ended up using:

recursionTable = (num, multi) => {
  if (num === 11) {
    return "We've hit the end of the recursion table.";
  } else {
    console.log(`${num} x ${multi} = ${num * multi}`);
  }
  return recursionTable(num   1, multi);
};

let num = 1;
console.log(recursionTable(num, 10));

/*
1 x 10 = 10
2 x 10 = 20
3 x 10 = 30
4 x 10 = 40
5 x 10 = 50
6 x 10 = 60
7 x 10 = 70
8 x 10 = 80
9 x 10 = 90
10 x 10 = 100
We've hit the end of the recursion table 
*/
  • Related