MD XF MD XF - 20 days ago 4
C Question

How would I shorten these for loops?

So I've got a program that runs through every possible alphanumerical combination between 0000000000 and ZZZZZZZZZZ. Currently I'm using this code:

for (digit[0] = 0; digit[0] < 36; digit[0]++)
for (digit[1] = 0; digit[1] < 36; digit[1]++)
for (digit[2] = 0; digit[2] < 36; digit[2]++)
// etc...

...and eventually there are 10 nested for loops and my entire editor screen is filled. So how would I condense this into one or two for loops? I can't find out how I would put them together testing and incrementing
. Thanks in advance to anyone who has this solution. I bet there's a million webpages on this but I couldn't think of how to phrase it in a google search.


Use an odometer algorithm. Increment the last digit. When it reaches the highest value, wrap it back to 0 and recurse on the remaining digits, until you run out of digits.

int increment_digit(int array[], unsigned int index, limit) {
    if (index == -1) { // We've wrapped around the entire set
        return 0;
    if (array[index] == limit) {
        array[index] = 0;
        return increment_digit(array, index-1, limit);
    } else {
        return 1;

int main(int argc, char **argv) {
    int digits[SIZE] = {0};
    while (1) {
        // do stuff ...
        if (!increment_digit(digits, SIZE-1, 36))
    return 0;