Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

integer

As a homework problem, I'm working on reading a decimal int from stdin, converting it to a different base (also provided from stdin) and printing it to the screen.

Here's what I've got so far:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, base, remainder, quotient;
    printf("please enter a positive number to convert: ");
    scanf("%d", &num);
    printf("please enter the base to convert to: ");
    scanf("%d", &base);

    remainder = quotient = 1;

    // validate input
    if (num < 0 || base < 0) {
        printf("Error - all numbers must be positive integers!\n");
        return 1;
    }

    // keep dividing to find remainders
    while (quotient > 0) {
        remainder = num % base;
        quotient = num / base;
        num = quotient;
        if (remainder >= 10) {
            printf("%c", remainder + 55);
        } else {
            printf("%d", remainder);
        }
    }   
    printf("\n");
    return 0;
}   

This works great, only that the algorithm this uses calculates the converted numbers from least significant to most significant digit, thus printing it in reverse. So, for example, converting 1020 to hexadecimal ( 0x3FC ) will print CF3.

Is there a trick I could use to reverse these numbers to print in the correct order. I can only use if-else, while, simple math operators and printf()/getchar()/scanf() - no functions, arrays or pointers. thanks.

like image 361
sa125 Avatar asked Dec 24 '09 10:12

sa125


People also ask

How do you reverse a number without an array?

you first count the digits of the given number in the FOR-loop in the shortest possible way. you need this because you have to 10-power each remainder up to digits of the given number in the next WHILE-loop and you store/add the result of this each time in the variable named SUM.

How do you reverse a number without using the function?

To reverse a number in PHP without using function declare a variable to store the reversed number, and initially assign zero to it. Now, extract the last digit from the original number, multiply the reverse number with 10, add the extracted digit to reversed number, and divide the original number by 10.


1 Answers

(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, then print it.

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

like image 184
Marco van de Voort Avatar answered Nov 15 '22 15:11

Marco van de Voort