0

Can someone please explain how to do make this work without a loop?

let x = prompt("Enter a first number to add:");
let y = prompt("Enter a second number to add:");
parseFloat(x);
parseFloat(y);

alert(peanoAddition(x, y));

function peanoAddition(x, y) {
  while (y !== 0) {
    if (y === 0) {
      return x;
    } else {
      x = x + 1;
      y = y - 1;
      return x;
    }
  }
}

customcommander
  • 17,580
  • 5
  • 58
  • 84
  • 1
    Your `return` statements don't really make sense, you always return from the first iteration of the loop, and if `y` is passed `0` then your function returns `undefined`. You probably meant `while (y != 0) { x += 1; y -= 1; } return x;` – Bergi Oct 19 '19 at 23:07
  • @Bergi: Thanks for your feedback. This is an exercise for a class I'm taking. The rules of the exercise state that this function is supposed to be recursive. Therefore using a loop is not allowed. – Ian Fischer Oct 30 '19 at 01:30

1 Answers1

1

This is fairly simple to change to a recursive function. Your terminating condition will be the same: if (y === 0) return x. Otherwise, you just call peanoAddition again with the new arguments for x and y and return the result.

Then, if y is not 0, the function gets called again and again until y is 0.

The following works exactly the same as your code. However, it keeps the same issues as well. For example, what happens when you call peanoAddition(5, -2)? Both your code and mine will run forever.

function peanoAddition(x, y) {
  if (y === 0) {
    return x;
  }
  return peanoAddition(x + 1, y - 1);
}
Ian
  • 5,704
  • 6
  • 40
  • 72
  • There's one thing I'd like to add that would be helpful: `function peanoAddition(x, y) { if (x === 0) { return y } else if (y === 0) { return x; } else { x++ y-- } return peanoAddition(x, y); }` Data validation wasn't a requirement. That's a good point. IF (x<0 || y <0 ) { //prompt for input?} – Ian Fischer Oct 30 '19 at 01:42