99 Bottles of Beer

This month’s Exercise involves coding the lyrics for a cumulative song. Perhaps the most famous, and certainly the most obnoxious, cumulative song is the old warhorse, 99 Bottles of Beer.

I don’t know anyone who sang the song all the way through, from 99 bottles down to the last one. And I remember singing the song most often in elementary school, where the notion of drinking beer was particularly naughty.

The cumulative song is easy to code. Here’s what I slapped together as a first stab:

#include <stdio.h>

int main()
{
    int b = 99;

    while(b)
    {
        printf("%d bottles of beer on the wall,\n",b);
        printf("%d bottles of beer!\n",b);
        printf("You take one down, pass it around,\n");
        b--;
        printf("%d bottles of beer on the wall!\n\n",b);
    }

    return(0);
}

I won’t bother displaying the entire output, but here is the final stanza:

1 bottles of beer on the wall,
1 bottles of beer!
You take one down, pass it around,
0 bottles of beer on the wall!

The last verse of the song presents a special case. Specifically, in human languages “1 bottles” is improper. It should be “1 bottle.” Not only that, the final line — if you ever bother really singing the entire thing — is You take it down, pass it around, No more bottles of beer!

To properly code that last stanza, I need to modify my quick-and-dirty code above. I could do that within the while loop with an ifelse structure. Instead, I opted for this solution:

#include <stdio.h>

int main()
{
    int b = 99;

    while(b > 1)
    {
        printf("%d bottles of beer on the wall,\n",b);
        printf("%d bottles of beer!\n",b);
        printf("You take one down, pass it around,\n");
        b--;
        printf("%d bottles of beer on the wall!\n\n",b);
    }
    printf("%d bottle of beer on the wall,\n",b);
    printf("%d bottle of beer!\n",b);
    printf("You take it down, pass it around,\n");
    printf("No more bottles of beer!\n\n");

    return(0);
}

The while loop counts down from 99 to 2. After it’s done, the printf() statements display the last stanza, which is grammatically proper for the final bottle of beer and last line of the song.

Leave a Reply