Python Program to Convert Decimal to Binary Using Recursion – 2022

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Convert Decimal to Binary Using Recursion.

Code

# Python Program to Convert Decimal to Binary Using Recursion

def convertToBinary(n):
    if n > 1:
        convertToBinary(n//2)
    print(n % 2,end = '')

# decimal number
dec = int(input('Enter a positive number -> '))

convertToBinary(dec)
print()

Output

Enter a positive number -> 20
10100
Enter a positive number -> 35
100011
Enter a positive number -> 30
11110
  • To convert decimal to binary using recursion we will keep on dividing the number by 2 and print if the current number is directly divisible by 2 or not in reverse order.
  • Suppose for 20, the flow will be like this:

num = 20 result=’10100′
num = 10 result=’1010′
num = 5 result=’101′
num = 2 result=’10’
num = 1 result=’1′

Check out our other python programming examples

Leave a Comment

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