Program opened below. You can scroll through the algorithm, Java code and output.
Program 37
Decimal to Binary Conversion Using Recursion
Question
Accept a non-negative decimal integer and display its binary equivalent using recursion.
Algorithm
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 program
Javaimport 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();
}
}
}Sample output
Input: Input: 10
Output: Binary = 1010