Search code examples
cprintingreverseradixansi-c

How to print values in reverse without the use of arrays nor pointers in C


I've been working on a code that converts a given number (decimal base) to any other base from 2 to 16.

Clearly, I've come across the issue that the function base_conversion_it (it stands for iterative) prints the values in reverse.

I cannot use arrays nor pointers, and everyone on the internet seems to solve this issue like that. My assignment requires making both an iterative and a recursive function (which I did and works).

void base_conversion_it(unsigned int n, unsigned int b) {

    if (n > 0) {

        //bases between 2 and 16
        if (b >= 2 && b <= 16) {

            int r;          //r = remainder
            int q = 1;      //quotient
            int num;        //saves the remainder

            while (q != 0) {

                r = n % b;
                printf("%X", r);

                q = n / b;
                n = q;
            }
        }
    }
}

Solution

  • You start converting from the units digit.
    Maybe start with the most significant digit instead?

    // It's Undefined Behaviour if `b` is outside the range [2...16]
    void base_conversion_it(unsigned int n, unsigned int b) {
        unsigned highestbase = 1;
        while (highestbase * b <= n) highestbase *= b; //possible wrap around and infinite loop
    
        while (highestbase) {
            printf("%X", n / highestbase);
            n %= highestbase;
            highestbase /= b;
        }
        printf("\n");
    }