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;
}
}
}
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 callpeanoAdditionagain with the new arguments forxandyand return the result.Then, if
yis not 0, the function gets called again and again untilyis 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.