4

I am coding a Lab exercise for one of my classes. The question asks to "Write a recursive function convert a decimal number into a binary number, printing the binary number" Using the constructor public static void decToBin(int num){}

Current code:

public class convert {
    public static void decToBin(int num) {
        if (num > 0) {
            decToBin(num /= 2);
            System.out.print(num % 2);
        }
    }

    public static void main(String[] args) {
        decToBin(50);
    }
}

Output: 011001

Unfortunately, when the program unpacks all the methods that were called and ends them it prints out my number in binary but backwards. I have tried just about everything under the sun and nothing works for me.

If anybody could tell me where the problem lies, give me a hint or anything. I just need a second opinion on this code. Thank you!

1
  • Not related, but wouldn't it print the wrong value for 1?
    – CBredlow
    May 30, 2017 at 23:09

2 Answers 2

3

You're dividing by 2 before you print out your answer which is messing with the result. The corrected function would be.

public static void decToBin(int num) {
    if (num > 0) {
        decToBin(num / 2);
        System.out.print(num % 2);
    }
}

Then to reverse the order, you can flip the lines.

public static void decToBin(int num) {
    if (num > 0) {
        System.out.print(num % 2);
        decToBin(num / 2);
    }
}
1
  • Thank you Kevin, it turns out the ' /= ' was the problem and all it needed was to be changed to ' / '
    – BigChemist
    May 30, 2017 at 23:18
0

First of all, you need to print num % 2 before calling the function on num /= 2. and you need to reverse the output to get the binary number because when converting to binary you type the numbers from right to left.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.