Need help, thanks in advance! For each of the following problems, write a method
ID: 3882225 • Letter: N
Question
Need help, thanks in advance! For each of the following problems, write a method that solves the problem. Demo each method you write by calling it in the main method. 1 99 Bottles of Beer Write a method that uses a for loop to print out the the lyrics of the infamous "99 Bottles of Beer on the Wall" drinking song. However, this method should take in an int as a parameter and start the lyrics from there. For example, if the method is called with 10 as the parameter, the output should be: 10 bottles of beer on the wall, 10 bottles of beer Take one down, pass it around, 9 bottles of beer on the wall 9 bottles of beer on the wall, 9 bottles of beer Take one down, pass it around, 8 bottles of beer on the wall (output continues in the same pattern) .. . 1 bottles of beer on the wall, 1 bottles of beer Take one down, pass it around, 0 bottles of beer on the wall
Explanation / Answer
main.cpp
#include <iostream>
using namespace std;
// Function to print the lyrics n number of times depending on the parameter numberOfTimes
void print(int numberOfTimes)
{
if(numberOfTimes == 1)
{
cout<<endl<<numberOfTimes<<" bottles of beer on the wall, "<<numberOfTimes<<" bottles of beer"<<endl;
cout<<"Take one down, pass it around, "<<numberOfTimes-1<<" bottles of beer on the wall"<<endl;
return;
}
// If numberOfTimes is greater than 1 print the lyrics and recursively call the print function with one less than the paramer
else
{
cout<<endl<<numberOfTimes<<" bottles of beer on the wall, "<<numberOfTimes<<" bottles of beer"<<endl;
cout<<"Take one down, pass it around, "<<numberOfTimes-1<<" bottles of beer on the wall"<<endl;
print(numberOfTimes-1);
return;
}
}
int main()
{
int numberOfTimes;
cout<<"Enter number of times to be printed: ";
cin>>numberOfTimes;
//number of times is greater than 0 print the lyrics
if(numberOfTimes > 0)
print(numberOfTimes);
else
cout<<endl<<"Enter number greater than 0";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.