Question
Program to convert decimal to binary number using recursion
ENTER DECIMAL NUMBER:125
THE BINARY VALUE OF DECIMAL NUMBER 125 IS 1111101
Enter the Decimal number:25
The binary value of 25 is 11001
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.*;
public class DecimalToBinaryUsingRecursion
{
public static long DecimalBinaryConversion(long dec)
{
if(dec==0)
{
return 0;
}
else
{
return (dec%2)+10*(DecimalBinaryConversion(dec/2));
}
}
public static void main()
{
long decimal=0,binary=0;
Scanner sc=new Scanner(System.in);
System.out.print("ENTER DECIMAL NUMBER:");
decimal=sc.nextLong();
if(decimal< 0)
{
binary=-DecimalBinaryConversion(-decimal);
/*
DecimalBinaryConversion(-decimal) will return positive binary number
but we want negative binary number so thats why
we added negative sign in front of DecimalBinaryConversion(-decimal)
*/
System.out.println("THE BINARY VALUE OF DECIMAL NUMBER "+decimal+" IS "+binary);
}
else
{
binary=DecimalBinaryConversion(decimal);
System.out.println("THE BINARY VALUE OF DECIMAL NUMBER "+decimal+" IS "+binary);
}
}
}
Python
def decimalToBinaryConvertor(decimal):
if(decimal==0):
return 0
else:
remainder=decimal%2
return remainder+10*decimalToBinaryConvertor(decimal//2)
if(__name__=='__main__'):
decimalNumber=int(input("Enter the Decimal number:"))
if(decimalNumber< 0):
binaryNumber = -decimalToBinaryConvertor(-decimalNumber)
# decimalToBinaryConvertor(-decimalNumber) will return positive binary number
# but we want negative binary number so thats why
# we added negative sign in front of decimalToBinaryConvertor(-decimalNumber)
print("The binary value of", decimalNumber, "is", binaryNumber)
else:
binaryNumber = decimalToBinaryConvertor(decimalNumber)
print("The binary value of",decimalNumber,"is",binaryNumber)
Coding Store
Sale
ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale