Python Program to Convert Decimal to Binary Using Recursion


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

Before we began to write the python program, lets try to understand what decimal and binary number mean.

Decimal is the base-10 number system used in everyday life, which uses 10 digits (0-9) to represent numbers. In the decimal system, each digit is assigned a place value based on its position, with the rightmost digit representing ones, the next digit representing tens, the next representing hundreds, and so on. For example, the number 532 in decimal notation represents 5 hundreds, 3 tens, and 2 ones.

Binary, on the other hand, is a base-2 number system used in computing and digital electronics, which uses only two digits (0 and 1) to represent numbers. In binary, each digit is assigned a place value based on its position, with the rightmost digit representing ones, the next digit representing twos, the next representing fours, and so on. For example, the binary number 1010 represents 1 eight, 0 fours, 1 two, and 0 ones, which is equal to the decimal number 10.


Python Code :

The below Python program converts a decimal number to its binary equivalent using recursion:


def decimal_to_binary(n):
    if n == 0:
        return 0
    else:
        return (n % 2) + 10 * decimal_to_binary(n // 2)

# Prompt user for input
decimal = int(input("Enter a decimal number: "))

# Check if input is valid
if decimal < 0:
    print("Please enter a non-negative integer.")
else:
    print("The binary equivalent of", decimal, "is", decimal_to_binary(decimal))

Explanation:

  1. The decimal_to_binary() function takes an integer n as input and recursively calculates its binary equivalent. The base case is when n is equal to 0, in which case the function returns 0. Otherwise, it returns the remainder of n divided by 2 (which is either 0 or 1) added to 10 times the binary equivalent of n divided by 2 (using integer division).

  2. The user is prompted to enter a decimal number.

  3. The input is checked to ensure it is a non-negative integer. If it is not, an error message is displayed.

  4. If the input is valid, the decimal_to_binary() function is called with decimal as the argument, and the result is displayed using the print() function.

For Example:


Enter a decimal number: 20
The binary equivalent of 20 is 10100


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co