Print the digits of a number in reverse order without arrays or functions

(removed original part of the post here, since it is not the solution)

THen the only solution I can see is to perform the loop that you have now the number of times that you have digits.

So first you calculate all digits till you get to the last, and then print it.

Then you take the original value + base and start dividing again till you come to the second "highest value" digit. Print it.

It is a double loop and you calculate everything twice, but you don't use extra storage.


It's a good try, and well phrased question. If only we had more people asking questions in such a clear manner!

The restrictions seem artificial. I guess you haven't learned about functions, arrays, pointers etc., in your class yet, but I think this problem is not meant to be solved elegantly without functions and/or arrays.

Anyway, you can do something like this:

curr := base
pow := 1
while num / curr >= 1 do:
    curr := curr * base
    pow := pow + 1

while pow >= 1:
    pow := pow - 1
    print floor(num / base ** pow)
    num := mod(num, base ** pow)

Basically, you are calculating how many digits you will need in the first loop, and then printing the digits in the correct order later.

Some specific issues with your code. I understand it's the beginning of a C class, but still, it's better to know of such issues now than to never realize them:

printf("please enter a positive number to convert: ");

You should add an fflush(stdout) after this to make sure the output appears before scanf() is called. By default, stdout is line buffered on many systems, so the prompt may not appear before your program waits for input.

printf("please enter the base to convert to: ");

Same as above.

    if (remainder >= 10) {
        printf("%c", remainder + 55);
    } else {
        printf("%d", remainder);
    }

You're assuming ASCII character set. This need not be true. But without arrays or pointers, there's no easy way to print the alphabets corresponding to 10.... Also, your code may print weird characters for base > 36.

You should also be aware that it's very hard to use scanf() safely. Hopefully you will learn better ways of getting input later.

Tags:

C

String

Integer