Counting in Alphabedecimal – Solution

Yes, it’s possible to code a program that counts in alphabedecimal from AAAA to ZZZZ without using nested loops. You must use a single loop, of course, but no cheating as shown in the original Exercise post.

The key is to use nested if statements instead of nested loops. Yes, something must be nested!

One loop is required, of course, because the program counts from AAAA to ZZZZ. I don’t want you to use goto statements, so for my solution I used a while loop that tests the strcmp() function. This function returns zero only when strings match:

while(strcmp(digits,"ZZZZ"))

Character array digits is initialized to hold the original string, "AAAA", which is incremented within the loop. As long as the value of digits doesn’t compare equally to string "ZZZZ", the loop spins.

To increment the loop, I compare each element in the digits array with the character 'Z'. If after incrementing the character, 'Z' is encountered, a nested if test repeats the same process for the next character in the array:

#include <stdio.h>
#include <string.h>

int main()
{
    char digits[] = "AAAA";

    while(strcmp(digits,"ZZZZ"))
    {
        puts(digits);
        digits[3]++;
        if( digits[3] > 'Z' )
        {
            digits[3] = 'A';
            digits[2]++;
            if( digits[2] > 'Z' )
            {
                digits[2] = 'A';
                digits[1]++;
                if( digits[1] > 'Z' )
                {
                    digits[1] = 'A';
                    digits[0]++;
                }
            }
        }
    }
    puts(digits);

    return(0);
}

A puts() statement is added at Line 28 to output the final string, "ZZZZ". That’s because the loop stops when the final string is built, so the puts() statement at Line 10 doesn’t send it to output.

I wasn’t really happy with this solution because it looks kind of clunky. I see items in the code that repeat, so I tried again with a function, inc(), to do the heavy-lifting:

#include <stdio.h>
#include <string.h>

#define TRUE 1
#define FALSE 0

int inc(char *a)
{
    *a += 1;
    if( *a > 'Z' )
    {
        *a = 'A';
        return(TRUE);
    }
    return(FALSE);
}

int main()
{
    char digits[] = "AAAA";

    while(strcmp(digits,"ZZZZ"))
    {
        puts(digits);
        if( inc(&digits[3]) )
            if( inc(&digits[2]) )
                if( inc(&digits[1]) )
                    inc(&digits[0]);
    }
    puts(digits);

    return(0);
}

In this rendition of the code, the main() function looks far more elegant.

I tried to reduce the inc() function, but my efforts resulted in a less-elegant version of the main() function. I also attempted to craft a recursive version of the solution, but my brain imploded.

If you solution resulted in the proper output without using a nested loop, great!

One thought on “Counting in Alphabedecimal – Solution

Leave a Reply