Python Program to Convert Decimal to Binary Using Recursion

By | October 3, 2021
Python Program to Convert Decimal to Binary Using Recursion

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

Steps:

  • 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.

Vamware
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

Code:

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)

Output 1:

Enter the Number: 8
8 in Binary is: 1000
Output 2
Enter the Number: 12
12 in Binary is: 1100

Output 3:

Enter the Number: 16
16 in Binary is: 10000

People are also reading:

  1. Python Program to Display Calendar
  2. WAP in C to Check Whether the Number is a Prime or not
  3. WAP in C++ & Python to calculate the size of each data types
  4. WAP to find the largest number amongst the numbers entered by the user
  5. Python Program to Find HCF or GCD
  6. WAP in C to check whether the number is a Palindrome number or not
  7. Python Program to Remove Punctuations From a String
  8. WAP to check whether a given character is an alphabet, digit or any special character
  9. WAP to swap two numbers
  10. Python Program to Find Sum of Natural Numbers Using Recursion

Leave a Reply

Your email address will not be published. Required fields are marked *