Python Program - Convert Decimal to Binary Using Recursion

ht‮:spt‬//www.theitroad.com

here's a Python program that converts a decimal number to binary using recursion:

# define a function to convert decimal to binary using recursion
def decimal_to_binary(n):
    if n > 1:
        decimal_to_binary(n // 2)
    print(n % 2, end='')

# get the decimal number from user
decimal = int(input("Enter a decimal number: "))

# call the decimal_to_binary function
decimal_to_binary(decimal)

In this program, we first define a function called decimal_to_binary that takes a decimal number as input and converts it to binary using recursion. If the number is greater than 1, we call the decimal_to_binary function again with the integer division of the number by 2. This continues until we reach a base case where the number is 1. At each step, we print out the remainder of the number divided by 2, which is the binary digit corresponding to that step.

We then use the input() function to get the decimal number from the user, and store it in the variable decimal.

We then call the decimal_to_binary() function with the decimal number decimal.

Finally, the binary representation of the decimal number is printed out on the console. Note that we use the end parameter of the print() function to suppress the newline character at the end of each print statement, so that the binary digits are printed on the same line.