Originally Posted by
Neo1
Well, you don't actually need to use nested loops for this problem. What you have at the moment will print all 99 versions of the first line of the song, and then afterwards it will print all versions of the second line.
Let's try and formalize what you want to happen, forget about C++ for a moment:
if n is the number of the current iteration, and the code runs 99 times, the output should be:
"n bottles of beer on the wall, n bottles of beer.
Take one down and pass it around, (n-1) bottles of beer on the wall."
Now, this should be reasonably easy to translate into C++. Use 1 for loop. Then run your code and find out if there are any special cases you need to handle. (There might be some grammar issues for n < 2, and for n = 0 you will have -1 bottles of beer on the wall :-) ) These can be fixed with an if inside the loop that check for certain values of n, or you can make it loop from 99 to 2 and then do the last 2 iterations "by hand".
I have no idea why the book wants you to solve this problem with nested loops, seems rather strange.
I made it ''by hand", but i have question: Why it starts from 98 instead of 99 if i write a line - cout<<endl; in my for loop?
Code:
#include <iostream>
using namespace std;
int main()
{
for(int i=99; i>=3 ;i--){
cout << i <<""<< " bottles of beer on the wall, "<<i<<" bottles of beer."<<endl;
cout << "Take one down and pass it around, " <<i-1<<" bottles of beer on the wall."<<endl;
cout <<endl;
}
cout <<"3"<< " bottles of beer on the wall, "<<"3"<<" bottles of beer."<<endl;
cout << "Take one down and pass it around, " <<"2"<<" bottles of beer on the wall."<<endl;
cout <<endl;
cout <<"2"<< " bottles of beer on the wall, "<<"2"<<" bottles of beer."<<endl;
cout << "Take one down and pass it around, " <<"1"<<" bottle of beer on the wall."<<endl;
cout <<endl;
cout <<"No more bottles of beer on the wall, no more bottles of beer."<<endl;
cout <<"Go to the store and buy some more, 99 bottles of beer on the wall."<<endl;
return 0;
}
I also tried to make an if statement in for loop, but it doesnt work as it should.
Code:
#include <iostream>
using namespace std;
int main()
{
for(int i=99; i>=3 ;i--){
if(i==1){
cout << i <<""<< " bottles of beer on the wall, "<<i<<" bottles of beer."<<endl;
cout << "Take one down and pass it around, " <<i-1<<" bottle of beer on the wall."<<endl;
cout <<endl;}
else
cout << i <<""<< " bottles of beer on the wall, "<<i<<" bottles of beer."<<endl;
cout << "Take one down and pass it around, " <<i-1<<" bottles of beer on the wall."<<endl;
cout <<endl;
}
cout <<"No more bottles of beer on the wall, no more bottles of beer."<<endl;
cout <<"Go to the store and buy some more, 99 bottles of beer on the wall."<<endl;
return 0;
}