Write a Java program to convert a decimal number to its binary equivalent using recursion


The code is correctly implementing the recursive algorithm to convert a decimal number to binary. The recursive function decimalToBinary takes an integer dec as input and returns an integer representing the binary equivalent of dec.

The function first checks if the input dec is 0, in which case it returns 0, which is the binary equivalent of 0. Otherwise, it returns the binary representation of dec by recursively calling decimalToBinary with dec divided by 2 and adding the remainder of dec modulo 2, which is the rightmost digit of the binary representation of dec, multiplied by 10 to the power of the number of digits already processed. This effectively shifts the existing digits one position to the left and adds the new rightmost digit at the end.

For example, if dec is 13, the first call to decimalToBinary with dec equal to 13 computes the remainder of 13 divided by 2, which is 1, and multiplies it by 10 to the power of 0, which is 1, resulting in 1. The recursive call to decimalToBinary with dec equal to 6 computes the remainder of 6 divided by 2, which is 0, and multiplies it by 10 to the power of 1, which is 10, resulting in 0. The recursive call to decimalToBinary with dec equal to 3 computes the remainder of 3 divided by 2, which is 1, and multiplies it by 10 to the power of 2, which is 100, resulting in 100. The recursive call to decimalToBinary with dec equal to 1 computes the remainder of 1 divided by 2, which is 1, and multiplies it by 10 to the power of 3, which is 1000, resulting in 1001. The final result returned by the initial call to decimalToBinary is 1001, which is the binary equivalent of 13.

The code is clear and well-organized. However, it could be improved by adding some error checking to handle negative input values, which would cause the function to enter an infinite recursion.

Source Code

import java.util.*;
public class DecToBin
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.printf("Enter the Decimal Number : ");
		int dec = input.nextInt();
		int bin = decimalToBinary(dec);
		System.out.printf("Binary Number : " + bin);
	}
	public static int decimalToBinary(int dec)
	{
		if(dec == 0)
		{
			return 0;
		}
		else
		{
			return (dec % 2 + 10 * decimalToBinary(dec / 2));
		}
	}
}

Output

Enter the Decimal Number : 23
Binary Number : 10111