Merry Cumulative Song Exercise – Solution

I crafted my solution to the cumulative song exercise by separating the parts of the song that are repeated from the unique text. Specifically, the ordinal days are unique as well as the gifts. The rest of the text is sung over and over.

Two arrays hold the repeating text, day[] for the days of Christmas and gift[] for the specific items.

The repeating text is On the _____ day of Christmas, my true love gave to me. That’s followed by each subsequent gift. An exception is the first day, where the line is A partridge in a pear tree. On subsequent days the line is And a partridge in a pear tree.

Here’s my solution:

#include <stdio.h>

int main()
{
    char *day[12] = { "first", "second", "third", "fourth",
        "fifth", "sixth", "seventh", "eighth", "ninth",
        "tenth", "eleventh", "twelfth" };
    char *gift[12] = {
        "And a partridge in a pear tree.",
        "Two turtle doves,",
        "Three French hens,",
        "Four calling birds,",
        "Five gold rings!",
        "Six geese a-laying,",
        "Seven swans a-swimming,",
        "Eight maids a-milking,",
        "Nine ladies dancing,",
        "Ten lords a-leaping,",
        "Eleven pipers piping,",
        "Twelve drummers drumming," };
    int d,g;

    for(d=0;d<12;d++)
    {
        printf("On the %s day of Christmas, my true love gave to me\n",
                day[d]);
        if( d == 0 )
        {
            printf("\tA partridge in a pear tree.\n\n");
        }
        else
        {
            for(g=d;g>0;g--)
                printf("\t%s\n",gift[g]);
            printf("\t%s\n\n",gift[g]);
        }
    }

    return(0);
}

Two loops manage the lyrics. The outer for loop at Line 23 counts up the 12 days of Christmas.

The 12 days are the days after Christmas, leading up to Twelfth Night (as in the Shakespeare play), the evening before the religious holiday Epiphany.

For the first day, when variable d is equal to zero (Line 27), the special text at Line 29 is displayed. Otherwise, the second, inner for loop works to rattle off the various gifts. That loop counts down from the value of variable d to zero.

Other solutions are possible, of course. Some C programmers get really clever and fish out all the repetitive words, tangling what’s left into a Gordian knot of unreadable text. The code then fishes out the words in the proper order in some amazing and incomprehensible fashion. I applaud you if you can craft such a solution.

Leave a Reply