Learning2Code4Life
Learning2Code4Life

Reputation: 5

How can I rewrite this function recursively?

Is there a way to use recursion to replace the for loop in this? I want it to print out the song 99 Bottles of Bear on the wall. I have been trying but I can not get it to work. Do I need to rewrite the code so that it can be rewritten recursively?

{
    function main() {
        input = Number(prompt("How many bottles do you have?"));

        for (let i=input; i > 0; --i){
            if (i == 1){
                console.log(i, "bottles of beer on the wall", i, "bottles of beer.");
                console.log("Take one down and pass it around, no more bottles of bear on the wall");
                console.log("No more bottles of bear on the wall, no more bottles of beer.");
                i = input;
                console.log("Go the store and buy some more,", i, "bottles of beer on the wall.")
                break;

            }else {
                console.log(i, "bottles of beer on the wall", i, "bottles of beer.");
                console.log("Take one down and pass it around,",i-1, "bottles of bear on the wall");
            }
        }
}
main();
}

Upvotes: 0

Views: 64

Answers (1)

Dominik
Dominik

Reputation: 6313

I would do it the below way:

function main(input, original) {
    if (!input) {
        input = Number(prompt('How many bottles do you have?'));
    }
  
    if(!original) {
        original = input;
    }

    if (input == 1) {
        console.log(`${input} bottles of beer on the wall ${input} bottles of beer.`);
        console.log('Take one down and pass it around, no more bottles of bear on the wall');
        console.log('No more bottles of beer on the wall, no more bottles of beer.');
        console.log(`Go the store and buy some more ${original} bottles of beer on the wall.`);
    } else {
        console.log(`${input} bottles of beer on the wall ${input} bottles of beer.`);
        console.log(`Take one down and pass it around, ${input - 1} bottles of beer on the wall`);
    }

    if (input > 1) {
        main(input - 1, original);
    }
}

main();

Upvotes: 1

Related Questions