In this Python program, we will create a recursive function to print the binary equivalent of an integer. Recursion is a technique where a function calls itself to solve a smaller version of the problem. By applying recursion, we can break down the conversion of an integer to binary into smaller steps until we reach the base case.
Problem Statement
Write a Python program to print the binary equivalent of an integer using recursion.
Python Program to Print Binary Equivalent of an Integer using Recursion
def decimal_to_binary(n):
if n > 1:
decimal_to_binary(n // 2)
print(n % 2, end='')
# Getting input from the user
num = int(input("Enter a decimal number: "))
# Printing the binary equivalent
print("Binary equivalent of", num, "is:", end=' ')
decimal_to_binary(num)How it works
- We define a recursive function
decimal_to_binarythat takes an integernas input. - Inside the function, we check if
nis greater than 1. If it is, we recursively call thedecimal_to_binaryfunction withn // 2. - This recursive call helps us to divide the number by 2 repeatedly until we reach the base case, which is when
nbecomes 1. - After the recursive call, we print the remainder of
ndivided by 2. This gives us the binary digit of the current step. - By using the
endparameter of theprintfunction and setting it to an empty string, we ensure that the binary digits are printed side by side without any line breaks. - Finally, we prompt the user to enter a decimal number, convert it to an integer using
int(input()), and call thedecimal_to_binaryfunction with the input number.
Input / Output
