MD XF
MD XF

Reputation: 8129

Increment array to a certain number

I have an integer array (representing a 4-digit number) that I need to increment so that each integer never goes higher than 3. Basically, it needs to print every 4-digit number that does not have 4 or higher in it. Here's the output I'm expecting compared to the actual output:

Expected: 0000 0001 0002 0003 0010 0011 0012 0013 0020 0021 0022 .... 3333
Received: 0000 1000 2000 3000 3100 3200 3300 3310 3320 3330 3331 3332

I know my algorithm's messed up but I don't know what to do to it:

int i, c[4];

memset(c, 0, sizeof(c));
i = 0;
while (1) {
    testprint(c);
    c[i]++;
    if (c[i] == 3)
        i++;
    if (i == 3)
        break;
}

All testprint does is display every digit in the array. So how should I change my code to correctly increment the array? And do I even need to use an array? How would I do this without one?

Upvotes: 0

Views: 194

Answers (3)

chqrlie
chqrlie

Reputation: 144695

You can use a function to convert a number into its representation in base 4 (ie: using only digits 0, 1, 2 and 3):

#include <stdio.h>

char *itoa4(unsigned value, char *dest, int digits) {
    dest[digits] = '\0';
    while (digits-- > 0) {
        dest[digits] = '0' + value % 4;
        value /= 4;
    }
    return dest;
}

int main(void) {
    char buf[5];
    for (int i = 0; i < 256; i++) {
        printf("%s\n", itoa4(i, buf, 4));
    }
    return 0;
}

Upvotes: 2

MD XF
MD XF

Reputation: 8129

All right, I found the answer with help from @chqrlie:

int *ito4(int value, int dest[])
{
    int i = 4;
    while (i-- > 0) {
        dest[i] = value % 4;
        value /= 4;
    }
    return dest;
}

int main(void)
{
    int i, arr[4];
    for (i = 0; i < 256; i++)
        print_array(ito4(i, buf), 4);
    return 0;
}

Upvotes: 0

Jack
Jack

Reputation: 133567

You don't need to use an array at all for this purpose. How you choose to represent a value and the value itself are two different things.

The same value, for example 10, can be represented in any different base you wish, it's 10 in base 10, 0xA in base 16, 12 in base 8 and so on.

At the same time incrementing a value by 1 works under every base. Assuming this you can easily just format an unsigned integer to print it as a base4 number.

Mind that with (value >> (i*2)) & 0x3 you extract the i-th digit, then everything becomes trivial.

Upvotes: -1

Related Questions