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.
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 integer
- Inside the function, we check if
nis greater than 1. If it is, we recursively call the
n // 2.
- This recursive call helps us to divide the number by 2 repeatedly until we reach the base case, which is when
- 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 the
- Finally, we prompt the user to enter a decimal number, convert it to an integer using
int(input()), and call the
decimal_to_binaryfunction with the input number.