Here in this article, we have provided a python source code that use the recursion function to convert the user entered Decimal number to the equivalent Binary Number.
Prerequisite topics to create this program.
- Python Input, Output
- Python User-Defined Function
- Python Recursion
- Python if…else statements
- Ask the user to enter a decimal number.
- Create a recursive function in which the function calls itself again and again till the base condition get satisfied.
- In recursive function first, we divide the number with 2 then again divide its quotient by 2, and again continuously divide its quotient till we get the quotient as 1.
- At last, we reverse back all the remainders of the division process, which will give us the equivalent Binary Format.
For example, if we want to covert the 34 into a binary number.
34 / 2 = quotient 17 remainder = 0 17/2 = quotient 8 remainder = 1 8/2 = quotient 4 remainder = 0 4/2 = quotient 2 remainder = 0 2/2 = quotient 1 remainder = 0 1/2 = quotient 1 remainder =1
Now we will write all reminders from bottom to top and this will give us the Binary number for 34.
(34)10 = (100010)2
Python Program to Convert Decimal to Binary Using Recursion
def decTobin(n): if n > 1: #this recursion will call for dectobin(n//2) decTobin(n//2) print(n % 2,end = '') num = int(input("Enter the Number: ")) print(num,"in Binary is:",end=" ") decTobin(num)
Enter the Number: 8 8 in Binary is: 1000
Output 2 Enter the Number: 12 12 in Binary is: 1100
Enter the Number: 16 16 in Binary is: 10000
People are also reading:
- Python Program to Display Calendar
- WAP in C to Check Whether the Number is a Prime or not
- WAP in C++ & Python to calculate the size of each data types
- WAP to find the largest number amongst the numbers entered by the user
- Python Program to Find HCF or GCD
- WAP in C to check whether the number is a Palindrome number or not
- Python Program to Remove Punctuations From a String
- WAP to check whether a given character is an alphabet, digit or any special character
- WAP to swap two numbers
- Python Program to Find Sum of Natural Numbers Using Recursion