Program opened below. You can scroll through the algorithm, Java code and output.

Decimal to Binary Conversion Using Recursion

Download .java

Question

Accept a non-negative decimal integer and display its binary equivalent using recursion.

Step 1: Start the program and accept a non-negative decimal integer. Step 2: If the input is negative, display an invalid-input message and stop. Step 3: Define a recursive method that prints the binary representation of a number. Step 4: If the number is greater than one, call the method with its quotient after division by two. Step 5: Wait for the recursive call to finish before printing the current remainder. Step 6: Print the remainder obtained by dividing the number by two. Step 7: This order prints the most significant binary digit first. Step 8: For input zero, print zero as its binary representation. Step 9: Return from each recursive call after printing its remainder. Step 10: Display a line break after the binary digits have been printed. Step 11: Stop the program.
Java
import java.util.*;
class DecimalBinary
{
    static void binary(int n)
    {
        if (n > 1)
        {
            binary(n / 2);
        }
        System.out.print(n % 2);
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a non-negative decimal number: ");
        int n = sc.nextInt();
        if (n < 0)
        {
            System.out.println("Invalid input");
        }
        else
        {
            System.out.print("Binary = ");
            binary(n);
            System.out.println();
        }
    }
}
Input: Input: 10 Output: Binary = 1010
← Previous Program 37 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.