O Christmas Tree


It’s Christmas time, nerds rejoice! Welcome this festive season with a bit of programming acumen to festoon your old CRT monitor with some yuletide cheer.

Multiple programming methods exist to output the Christmas tree shown above. The simplest way, probably how I would have coded the thing in BASIC back in the 1980s, would be to output each line by itself. A stack of 20 PRINT statements generates the tree, adorning the glowing (and irritating) white phosphor on my beloved old TRS-80 Model III.

For the C language, however, I sought to be clever. Ideally I’d love to use a single statement in a loop to output the Christmas tree. Such would be a thing of beauty.

Alas, the C language lacks a function that outputs a string of the same character. For example, generating a line of asterisks with a given length. Other programming languages have such tools, but in C you must code them on your own. I cover such a function for next week’s Lesson, but for now, here’s my attempt to tightly code Christmas tree output:

2022_12_24-Lesson.c

#include <stdio.h>

int main()
{
    int x,y,stars;
    const int height = 20;    /* 20 rows tall */

    for( x=0,stars=1 ; x<height; x++,stars+=2 )
    {
        /* print the indent */
        printf("%*c",height-x,' ');
        for( y=0; y<stars; y++ )
        {
            putchar('*');    
        }
        putchar('\n');
    }

    return(0);
}

Line 6 sets the tree’s height at 20 rows, which fits well on a standard 80 column by 24 row text screen.

The for loop at Line 8 modifies two conditions. The first is x, which is the row count, capped at the value of integer constant height. The second is stars, which are the asterisks that create the tree. This value is increased by two each iteration of the for loop: stars+=2. The two extra asterisks account for the tree’s triangular shape.

Within the loop, a printf() statement outputs a given length of spaces. The variable width specifier, *, sets the number of spaces output, which is inversely proportional to the row height, minus x.

I wanted to use a similar printf() placeholder to output the row of asterisks, but here is where the standard C library lacks a function to output a string of repeated characters. I tried using a variable width argument, but it works best only with spaces. Alas.

To generate the Christmas tree branches, I use a nested for loop, with the value of stars to create ever increasing evergreen branches.

A final putchar() statement spews out the newline, ending each row.

This kind of simple and fun output is often used as a programming problem, especially for an obfuscated C challenge. Multiple ways exist to output the tree. If you feel like exercising your C programming kung fu, consider attempting this challenge. How would you output a simple Christmas tree pattern as shown above?

Leave a Reply