Having Fun with goto – Solution

This month’s C programming Exercise is probably the most bizarre one I’ve ever offered! Using the goto keyword is frowned upon, which means that your C programmer brain is unaccustomed to thinking about using goto to construct, well, anything!

For me, it’s been a while since I coded in BASIC, which uses a GOTO command to hop around the code. More relevant, however, is Assembly language: Assembly uses “jump” operands as branching instructions. In fact, the goto format in C heavily resembles the jump operand format used in Assembly. So this type of challenge may have been a bit easier for me to code, though it’s still weird.

Here is my solution:

2025_11-Exercise.c

#include <stdio.h>

int main()
{
    int a = 0;
    char b = 'A';

output:
    if( a==10 ) goto end;
    printf("%c%d  ",b,a);
    b++;
    if( b=='K' )
    {
        putchar('\n');
        a++;
        b='A';
    }
    goto output;

end:
    return 0;
}

This code doesn’t even look like C — but it is!

The first label is output, which is kinda the start of the outer nested loop. It’s followed by an if statement to test the value of variable a. When a is equal to 10, execution branches to the end label, the program is done. Otherwise, the program outputs the values of variables b and a, which have been initialized to ‘A’ and zero, respectively.

Variable b tracks the inner loop. An if test determines when b is equal to ‘K’. If true, the newline is output, variable a is incremented (for the next row of output), and variable b is reset back to the value ‘A’.

When variable b is less than ‘K’, a goto statement jumps execution back to the output label, where the process repeats.

Here is sample output, which is identical to the (more proper) nested loop version of the code:

A0  B0  C0  D0  E0  F0  G0  H0  I0  J0  
A1  B1  C1  D1  E1  F1  G1  H1  I1  J1  
A2  B2  C2  D2  E2  F2  G2  H2  I2  J2  
A3  B3  C3  D3  E3  F3  G3  H3  I3  J3  
A4  B4  C4  D4  E4  F4  G4  H4  I4  J4  
A5  B5  C5  D5  E5  F5  G5  H5  I5  J5  
A6  B6  C6  D6  E6  F6  G6  H6  I6  J6  
A7  B7  C7  D7  E7  F7  G7  H7  I7  J7  
A8  B8  C8  D8  E8  F8  G8  H8  I8  J8  
A9  B9  C9  D9  E9  F9  G9  H9  I9  J9  

I hope that you can see how goto made a nested loop not look like a nested loop. The code above still has a poetic beauty to it, but its purpose is obfuscated. Even an experienced programmer must step through the code line by line to determine what exactly is going on.

Remember that your solution need not look exactly like mine. In fact, if you have a different solution, consider pasting it in the comments. Use the <pre> tags to ensure that the formatting doesn’t go all bonkers.

Leave a Reply