Alphabedecimal Revisited

Difficulty: Medium

The goal of the November 2018 Exercise on this blog was to count in “alphabedecimal,” or base 26 using the uppercase letters of the alphabet. The solution cycles from AAAA to ZZZZ flipping each character (or digit) one at a time, just as numbers are counted. The challenge is to do so without employing a nested loop.

The Exercise’s solution used a complex if structure to determine when to change digits — and to avoid the dreaded nested loop. I provided two copies of the solution. The second one is shown here:

2021_10_01-Lesson.c

#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 the main() function, each if statement in the cascading structure examines a different character in the digits[] string. The inc() function is called to increment a character at a specific position. If the character is greater than 'Z', it’s reset to 'A' with the next character in the array incremented. This solution works, but it’s clunky.

Your task for this month’s Exercise is to recreate the program’s output, generating alphabedcimal values from AAAA through ZZZZ. Unlike the solution from three years ago, you cannot use a cascading if structure &mdash or a nested loop. While your solution can use the same philosophy that’s employed by the inc() function (shown above), though the the key is to use recursion to perform this task. This recursive function avoids the nested if structure and clumsy way it references the digits in the array.

Please try this Exercise on your own, devising a recursive function to handle the character/digit flipping. Click here to view my solution.

Leave a Reply