Help!For "Ninety-nine Bottles of Beer on the wall"

This is a discussion on Help!For "Ninety-nine Bottles of Beer on the wall" within the C++ Programming forums, part of the General Programming Boards category; I am studying in LA,PCC college.Now we use book Problem Solving with C++ 6th edition,Author:Walter Savitch.in page 244 problem 13: ...

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    67

    Unhappy Help!For "Ninety-nine Bottles of Beer on the wall"

    I am studying in LA,PCC college.Now we use book Problem Solving with C++ 6th edition,Author:Walter Savitch.in page 244 problem 13:
    write a program that outputs the lyrics for the song "Ninety-nine Bottles of Beer on the wall".You should print the number of bottles in English,not as a number.EX:

    Ninety-nine bottles of beer on the wall,
    Ninety-nine bottles of beer,
    Take one down,pass it around,
    Ninety-eight bottles of beer on the wall.
    ............
    One bottle of beer on the wall,
    One bottle of beer,
    Take one down,pass it around,
    Zero bottles of beer on the wall.

    Design your program with a function that takes as an argument an Integer between 0 and 99 and returns a string that contains the integer value in English.Your program should not have 100 different if-else statement!Instead,use % and / to extract the tens and ones digits to construct the English string.

    And this is my code(I think it is really really bad !!!!But it is absolutely correct!)
    Code:
    
    #include <iostream>
    
    using namespace std;
    int main()
    {
        cout<<"Welcom to 99 Bottles of Beer on the wall!\n"
            <<"Please enter the number you want and we will give you the corresponding lyric:";
        int num;
        cin>>num;   
        
        
        if(num<=99&&num>0)
       { int x,y;
        x=num/10;
        y=num%10;
         switch(num)
         {
              case 1:cout<<"One";
              break;
              case 2:cout<<"Two";
              break;
              case 3:cout<<"Three";
              break;
              case 4:cout<<"Four";
              break;
              case 5:cout<<"Five";
              break;
              case 6:cout<<"Six";
              break;
              case 7:cout<<"Seven";
              break;
              case 8:cout<<"Eight";
              break;
              case 9:cout<<"Nine";
              break;
              }  
        switch(num)
           {
              case 10:cout<<"Ten";
              break;
              case 11:cout<<"Eleven";
              break;
              case 12:cout<<"Twelve";
              break;
              case 13:cout<<"Thirteen";
              break;
              case 14:cout<<"Fourteen";
              break;
              case 15:cout<<"Fifteen";
              break;
              case 16:cout<<"Sixteen";
              break;
              case 17:cout<<"Seventeen";
              break;
              case 18:cout<<"Eighteen";
              break;
              case 19:cout<<"Nineteen";
              break;}
         switch(x)
        {
           case 2:cout<<"Twenty";
           break;
           case 3:cout<<"Thirty";
           break;
           case 4:cout<<"Forty";
           break;
           case 5:cout<<"Fifty";
           break;
           case 6:cout<<"Sixty";
           break;
           case 7:cout<<"Seventy";
           break;
           case 8:cout<<"Eighty";
           break;
           case 9:cout<<"Ninety";
           break;
           }
           if(num>20)
          { switch(y)
         {
              case 1:cout<<"-one";
              break;
              case 2:cout<<"-two";
              break;
              case 3:cout<<"-three";
              break;
              case 4:cout<<"-four";
              break;
              case 5:cout<<"-five";
              break;
              case 6:cout<<"-six";
              break;
              case 7:cout<<"-seven";
              break;
              case 8:cout<<"-eight";
              break;
              case 9:cout<<"-nine";
              break;
              }}
              if(num==1)
              cout<<" bottle of beer on the wall,\n";
              else
              cout<<" bottles of beer on the wall,\n";
          switch(num)
         {
              case 1:cout<<"One";
              break;
              case 2:cout<<"Two";
              break;
              case 3:cout<<"Three";
              break;
              case 4:cout<<"Four";
              break;
              case 5:cout<<"Five";
              break;
              case 6:cout<<"Six";
              break;
              case 7:cout<<"Seven";
              break;
              case 8:cout<<"Eight";
              break;
              case 9:cout<<"Nine";
              break;
              }  
        switch(num)
           {
              case 10:cout<<"Ten";
              break;
              case 11:cout<<"Eleven";
              break;
              case 12:cout<<"Twelve";
              break;
              case 13:cout<<"Thirteen";
              break;
              case 14:cout<<"Fourteen";
              break;
              case 15:cout<<"Fifteen";
              break;
              case 16:cout<<"Sixteen";
              break;
              case 17:cout<<"Seventeen";
              break;
              case 18:cout<<"Eighteen";
              break;
              case 19:cout<<"Nineteen";
              break;}
         switch(x)
        {
           case 2:cout<<"Twenty";
           break;
           case 3:cout<<"Thirty";
           break;
           case 4:cout<<"Forty";
           break;
           case 5:cout<<"Fifty";
           break;
           case 6:cout<<"Sixty";
           break;
           case 7:cout<<"Seventy";
           break;
           case 8:cout<<"Eighty";
           break;
           case 9:cout<<"Ninety";
           break;
           }
           if(num>20)
          { switch(y)
         {
              case 1:cout<<"-one";
              break;
              case 2:cout<<"-two";
              break;
              case 3:cout<<"-three";
              break;
              case 4:cout<<"-four";
              break;
              case 5:cout<<"-five";
              break;
              case 6:cout<<"-six";
              break;
              case 7:cout<<"-seven";
              break;
              case 8:cout<<"-eight";
              break;
              case 9:cout<<"-nine";
              break;
              }}
              if(num==1)
              cout<<" bottle of beer,\n"
              <<"Take one down,pass it around,\n"; 
            else
              cout<<" bottles of beer,\n"
            <<"Take one down,pass it around,\n";
        int p,q;
        p=(num-1)/10;
        q=(num-1)%10;
         switch(num-1)
         {
              case 0:cout<<"Zero";
              break;        
              case 1:cout<<"One";
              break;
              case 2:cout<<"Two";
              break;
              case 3:cout<<"Three";
              break;
              case 4:cout<<"Four";
              break;
              case 5:cout<<"Five";
              break;
              case 6:cout<<"Six";
              break;
              case 7:cout<<"Seven";
              break;
              case 8:cout<<"Eight";
              break;
              case 9:cout<<"Nine";
              break;
              }  
        switch(num-1)
           {
              case 10:cout<<"Ten";
              break;
              case 11:cout<<"Eleven";
              break;
              case 12:cout<<"Twelve";
              break;
              case 13:cout<<"Thirteen";
              break;
              case 14:cout<<"Fourteen";
              break;
              case 15:cout<<"Fifteen";
              break;
              case 16:cout<<"Sixteen";
              break;
              case 17:cout<<"Seventeen";
              break;
              case 18:cout<<"Eighteen";
              break;
              case 19:cout<<"Nineteen";
              break;}
         switch(p)
        {
           case 2:cout<<"Twenty";
           break;
           case 3:cout<<"Thirty";
           break;
           case 4:cout<<"Forty";
           break;
           case 5:cout<<"Fifty";
           break;
           case 6:cout<<"Sixty";
           break;
           case 7:cout<<"Seventy";
           break;
           case 8:cout<<"Eighty";
           break;
           case 9:cout<<"Ninety";
           break;
           }
           if(num-1>20)
          { switch(q)
         {
                      
              case 1:cout<<"-one";
              break;
              case 2:cout<<"-two";
              break;
              case 3:cout<<"-three";
              break;
              case 4:cout<<"-four";
              break;
              case 5:cout<<"-five";
              break;
              case 6:cout<<"-six";
              break;
              case 7:cout<<"-seven";
              break;
              case 8:cout<<"-eight";
              break;
              case 9:cout<<"-nine";
              break;
              
              }}
              if(num==2)
              cout<<" bottle of beer on the wall.\n";
              else
              cout<<" bottles of beer on the wall.\n";
              }
              
              else 
              cout<<"Invalid number!"<<endl;
              system("pause");
              return 0;
              }
    I want to make it more easy and small.So can I use function call like this:
    int num;
    cin>>num;
    switch(num)
    {
    case 1:
    return "One";
    break;
    case 2:
    return "Two";
    break;
    ..........}
    Because in my code there are many things are the same.
    And also what is the type for "some words"?Is it string?
    Can I let some variable (EX:X) equals to a string?
    Thanks !
    Super Beginner
    Last edited by tx1988; 05-08-2007 at 04:29 PM.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,541
    http://www.99-bottles-of-beer.net/

    Well, 1-19 are the awkward cases, and 20 onwards is completely regular.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Wow.... why use so many switch statements? There are better ways of dong this. Here's one:

    Code:
    std::string a_szNum[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
    This means whenever you use a_szNum[i], you'll get the string representation of i.

    As Salem was saying, you could do this kind of thing for 1 to 19. After you hit 20, you're building strings off of the multiple of 10 + whatever is in the one's column.

  4. #4
    semi-colon generator ChaosEngine's Avatar
    Join Date
    Sep 2005
    Location
    Chch, NZ
    Posts
    597
    it's pointless. you will never do better than the perl version.
    Code:
        ''=~(        '(?{'        .('`'        |'%')        .('['        ^'-')
        .('`'        |'!')        .('`'        |',')        .'"'.        '\\$'
        .'=='        .('['        ^'+')        .('`'        |'/')        .('['
        ^'+')        .'||'        .(';'        &'=')        .(';'        &'=')
        .';-'        .'-'.        '\\$'        .'=;'        .('['        ^'(')
        .('['        ^'.')        .('`'        |'"')        .('!'        ^'+')
       .'_\\{'      .'(\\$'      .';=('.      '\\$=|'      ."\|".(      '`'^'.'
      ).(('`')|    '/').').'    .'\\"'.+(    '{'^'[').    ('`'|'"')    .('`'|'/'
     ).('['^'/')  .('['^'/').  ('`'|',').(  '`'|('%')).  '\\".\\"'.(  '['^('(')).
     '\\"'.('['^  '#').'!!--'  .'\\$=.\\"'  .('{'^'[').  ('`'|'/').(  '`'|"\&").(
     '{'^"\[").(  '`'|"\"").(  '`'|"\%").(  '`'|"\%").(  '['^(')')).  '\\").\\"'.
     ('{'^'[').(  '`'|"\/").(  '`'|"\.").(  '{'^"\[").(  '['^"\/").(  '`'|"\(").(
     '`'|"\%").(  '{'^"\[").(  '['^"\,").(  '`'|"\!").(  '`'|"\,").(  '`'|(',')).
     '\\"\\}'.+(  '['^"\+").(  '['^"\)").(  '`'|"\)").(  '`'|"\.").(  '['^('/')).
     '+_,\\",'.(  '{'^('[')).  ('\\$;!').(  '!'^"\+").(  '{'^"\/").(  '`'|"\!").(
     '`'|"\+").(  '`'|"\%").(  '{'^"\[").(  '`'|"\/").(  '`'|"\.").(  '`'|"\%").(
     '{'^"\[").(  '`'|"\$").(  '`'|"\/").(  '['^"\,").(  '`'|('.')).  ','.(('{')^
     '[').("\["^  '+').("\`"|  '!').("\["^  '(').("\["^  '(').("\{"^  '[').("\`"|
     ')').("\["^  '/').("\{"^  '[').("\`"|  '!').("\["^  ')').("\`"|  '/').("\["^
     '.').("\`"|  '.').("\`"|  '$')."\,".(  '!'^('+')).  '\\",_,\\"'  .'!'.("\!"^
     '+').("\!"^  '+').'\\"'.  ('['^',').(  '`'|"\(").(  '`'|"\)").(  '`'|"\,").(
     '`'|('%')).  '++\\$="})'  );$:=('.')^  '~';$~='@'|  '(';$^=')'^  '[';$/='`';
    that actually works!
    "I saw a sign that said 'Drink Canada Dry', so I started"
    -- Brendan Behan

    Free Compiler: Visual C++ 2005 Express
    If you program in C++, you need Boost. You should also know how to use the Standard Library (STL). Want to make games? After reading this, I don't like WxWidgets anymore. Want to add some scripting to your App?

  5. #5
    Registered User
    Join Date
    May 2007
    Posts
    14
    Hope this helps..

    Your solution should consist of implementations of the following two functions:

    string numToEnglish(int num);
    void printStanza(int numStanzas);

    The numToEnglish function should return a string with the English words for the number between 0 and 99 passed as an argument. The printStanza function should output a single stanza for the number of bottles of beer passed in as an argument. printStanza should call numToEnglish
    In numToEnglish, use the / and % operators to determine the tens and ones digits, then use a switch or if-then-else statement to generate a string based on the tens and ones values.
    Review "Arithmetic Operators and Expressions" in Section 2.3 for more information on using the / and % operators for integer division.
    You may use the + operator to concatenate two strings. For example, after executing the following code:
    Code:
    string num = "ninety";
    num = num + " ";
    num = num + "two";
    The variable num will contain the string "ninety two".
    The definition of a function that returns a string has the same fundamental structure as the functions in the chapter that return numeric values. The following is a simple illustration of a function that returns a string:
    Code:
    string aStringFunction(int num)
    {
        string result = "";
        if (num == 5)
        {
            result = "correct";
        }
        else
        {
            result = "incorrect";
        }
        return result;
    }
    The printStanza function has return type void. This means that it does not return a value, and does not need to include a return statement. If it does include a return statement, a value may not follow the return keyword. The following is a simple example of the use of the return statement in a void function:
    Code:
    void aVoidFunction(int num)
    {
        if (num == 4)
        {
            return;
        }
        cout << "The number was not 4" << endl;
        return;
    }
    void functions will be discussed in more detail in Section 5.1
    The printStanza function should print a single stanza of the song for the number of beers passed in as an argument. You should check for the case of a single bottle of beer to make sure that you use the word "bottle" rather than "bottles".

  6. #6
    Registered User
    Join Date
    May 2007
    Posts
    14
    also, it is easier if you only have 3 switch statements..such as

    switch (num) , switch (tens), and switch (ones)

  7. #7
    Registered User
    Join Date
    May 2007
    Posts
    67

    Wink Thanks!

    Thank you for everyone's help!I am only learn programming for 2 months,so there are many many things that I don't know.I am so glad that you guys can help me,I will take your good advice.

  8. #8
    Registered User
    Join Date
    May 2007
    Posts
    67

    Question

    Code:
    string aStringFunction(int num)
    {
        string result = "";
        if (num == 5)
        {
            result = "correct";
        }
        else
        {
            result = "incorrect";
        }
        return result;
    }
    I try your code for string function,but my compiler said `string' does not name a type.I use BloodDEV-C++ 4.9.9.2.
    Last edited by tx1988; 05-09-2007 at 10:38 AM.

  9. #9
    Registered User
    Join Date
    May 2007
    Posts
    67

    Question

    Code:
    std::string a_szNum[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
    I don't know how to use this code.
    do you mean I should make it like this:
    Code:
    #include <iostream>
    #include <string>
    using namespac estd;
    int main()
    {
        int i=0;
        cin>>i;
        string num[i] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
    cout<<num[i];
    But my compiler said variable-sized object `num' may not be initialized.What is that mean?How to make your code work?

  10. #10
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Mmm, no you're using it all wrong. The idea is that you're creating an array of strings. So you create the array as I showed, not like how you put an index in the declaration.

    Anyway, here's an example:

    Code:
    #include <iostream>
    
    int main(int argc, char *argv[])
    {
    	int i;
    	std::string a_szNum[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
    	
    	for(i=0;i<10;i++)
    	{
    		std::cout << "a_szNum[" << i << "] = " << a_szNum[i] << std::endl;
    	}
    	
    	return 0;
    }
    See how it can be used?

    You can write a function to return a string based upon the number. Here's an ugly way of doing it with the string array being global:

    Code:
    #include <iostream>
    
    std::string getNum(int);
    
    std::string a_szNum[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
    
    int main(int argc, char *argv[])
    {
    	int i;
    	
    	for(i=0;i<10;i++)
    	{
    		std::cout << "a_szNum[" << i << "] = " << getNum(i) << std::endl;
    	}
    	
    	return 0;
    }
    
    std::string getNum(int iNum)
    {
    	return a_szNum[iNum];
    }

  11. #11
    0x01
    Join Date
    Sep 2001
    Posts
    88
    Code:
    #include <iostream>
    using namespace std;
    
    const char * ONES[] = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", 
                            "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
    const char * TENS[] = { "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
    
    char * retFixedLyrics(char * str, unsigned short n)
    {
    	if (n >= 20)
    	{
    		strcpy(str, TENS[ (n / 10)-2 ]);
    
    		if (n &#37; 10)
    		{
    			strcat(str, "-");
    			strcat(str, ONES[n % 10]);
    		}
    	}
    	else
    		strcpy(str, ONES[n]);
    
    	return str; // incase cout << retFixedLyrics(...);
    }
    
    #define MAX 14 // seventy + -seven = 13 w/o spaces
    
    int main()
    {
    	char lyrics[MAX];
    	unsigned short n;
    
    	cout << "N Bottle(s) of Beer on the Wall!" << endl;
    
    	do
    	{
    		cout << "#" << ends;
    		cin >> n; 
    
    		if (n > 99) continue;
    
    		cout << retFixedLyrics(lyrics, n) << " Bottle(s) of beer on the wall!" << endl;
    		cout << lyrics <<  " Bottle(s) of beer!" << endl;
    
    		if (n)
    			cout << "Take one down, pass it around." << endl;
    		else
    			cout << "?...There isn't any beer left." << endl;
    	}
    	while (n != 0);
    
    	return 0;
    }
    Output
    -------
    N Bottle(s) of Beer on the Wall!
    # 77
    Seventy-Seven Bottle(s) of beer on the wall!
    Seventy-Seven Bottle(s) of beer!
    Take one down, pass it around.
    # 0
    Zero Bottle(s) of beer on the wall!
    Zero Bottle(s) of beer!
    ?...There isn't any beer left.
    Last edited by knave; 05-09-2007 at 03:57 PM. Reason: Added if (n) ... else ...

  12. #12
    Registered User
    Join Date
    May 2007
    Posts
    67

    Cool O!I am crying~~~~

    Thank you really really very much to everyone!!!!!!
    I asked this question to my 2 professors,but they just let me use switch statement,and they tell me you can't define a string function.I have nothing to say about them.(Maybe professor in college are always like this,at least in my view.)
    I am so thankful to cry~~~~~(wu~~~wu~~~wu~~~)
    But I am sure I will need all you guys help in my future study.But I won't let you guys do the homework or exam for me,I will think them carefully then if I am really in trouble I will put on my code for asking help!

  13. #13
    Registered User
    Join Date
    Sep 2007
    Posts
    1

    Bottles of beer

    Something the original poster should have pointed out, the solution had to comply with only those topics covered in chapters 1 thru 3 of that book.

    Strings and arrays aren't covered yet.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 99 Bottles of Beer...
    By Mister C in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 06-19-2007, 04:43 PM
  2. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM
  3. July is American Beer Month!
    By Govtcheez in forum A Brief History of Cprogramming.com
    Replies: 23
    Last Post: 06-30-2004, 10:15 PM
  4. Excuses to drink.
    By C_Coder in forum A Brief History of Cprogramming.com
    Replies: 25
    Last Post: 08-14-2002, 05:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21