Write a program to to Convert Decimal to Binary Using Recursion in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 | def convertToBinary(n): # Function to print binary number for the input decimal using recursion if n > 1: convertToBinary(n//2) print(n % 2,end = '') # decimal number dec = int(input("Enter a number:")) convertToBinary(dec) |
This Python program uses a recursive function “convertToBinary()” to convert a decimal number to its binary representation. The function takes an input argument “n” and checks if it is greater than 1. If it is, the function recursively calls itself with the value of “n” divided by 2 as the argument. This operation keeps dividing the number by 2 until the quotient becomes less than or equal to 1.
The program also takes input from the user in the form of an integer using the “input()” function and assigns it to the variable “dec”. The function “convertToBinary()” is then called with the input number as the argument. Inside the function, the remainder of n%2 is printed for each recursive call, with the end parameter set to empty so that the output is printed in a single line.
Example output:

