Counting in Alphabedecimal

In C, you can easily count from 000 to 999 (decimal), from 000 to 777 (octal), and from 000 to FFF (hexadecimal). These examples are in bases 10, 8, and 16, respectively. When it comes to counting from AAAA to ZZZZ, however, you must code your own routine.

I’ll call this numbering scheme alphabedecimal. It’s base 26, with digits from A (zero) through Z (25). This is all just trivia to sate my inner geek.

Counting from AAAA through ZZZZ is a permutation problem, which I’ve written about before. In fact, the solution is quite easy when you use nested for loops like this:

#include <stdio.h>

int main()
{
    char digits[5];

    /* Terminate string */
    digits[4] = '\0';
    /* generate permutations */
    for(digits[0] = 'A'; digits[0] <= 'Z' ; digits[0]++)
        for(digits[1] = 'A'; digits[1] <= 'Z' ; digits[1]++)
            for(digits[2] = 'A'; digits[2] <= 'Z' ; digits[2]++)
                for(digits[3] = 'A'; digits[3] <= 'Z' ; digits[3]++)
                    puts(digits);

    return(0);
}

The output for this code shows alphabedecimal values from AAAA through ZZZZ.

Your challenge for this month’s Exercise is to generate similar output, but without using nested loops: Process a string of four characters, incrementing from AAAA to AAAB, AAAC, and so on up to ZZZZ. The output must be identical the sample program above, just without using any nested loop.

Please try this Exercise on your own before you peek at my solution.

Leave a Reply