0

I'm trying to solve this program using recursive function which is needed for our program. The program is converting a decimal number system from a decimal 16 divided to a base of 2 using recursion, but my problem is that instead of the expected output of 10000 somehow it is reversed into 00001.

public static void main(String[] args) {
    int decimalValue = 0;
    int targetBase = 0;

    while (decimalValue != -1){
        Scanner input = new Scanner(System.in);

        System.out.print("Decimal value: ");
        decimalValue = input.nextInt();

        if (decimalValue == -1){
            System.out.println("Thank you for using the program. bye!");
            System.exit(0);
        }
        while (targetBase < 2 || targetBase > 16){
            System.out.print("Target base: ");
            targetBase = input.nextInt();
        }

        System.out.print("Value of " + decimalValue + " in base " + targetBase + " is ");
        recursionFunction(decimalValue, targetBase);

        targetBase = 0;
    }
}

public static void recursionFunction(int Decimal, int Base){
    int result,test1;

    if (Decimal == 0) {
        System.out.println(" " );
        return;
    }

    result = Decimal / Base;

    System.out.print(Decimal % Base);

    recursionFunction(result, Base);

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Murd
  • 1
  • Does this answer your question? [Issue with recursion - I don't understand why I get a reverse output](https://stackoverflow.com/questions/43572145/issue-with-recursion-i-dont-understand-why-i-get-a-reverse-output) – Ivar Oct 15 '21 at 15:35
  • "Somehow"? That's the exact algorithm you wrote. Just go through it with pen and paper if you must: Let's say you input "100" as number and "10" as base. Your code does: "100 / 10", and stores that result for the next run (so, '10'). Then it does '100 % 10' (which is 0) and prints that. Reversing is an intrinsic part of the exercise, you're supposed to write that code for this homework exercise. – rzwitserloot Oct 15 '21 at 15:36

0 Answers0