SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
5.recursion
Exercise:
Programming Excercises
Question:19 | ISBN:978013274719 | Edition: 6

Question

(Decimal to binary) Write a recursive function that converts a decimal number into a binary number as a string. The function header is as follows:
def decimalToBinary(value):
Write a test program that prompts the user to enter a decimal number and displays its binary equivalent.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Decimal to binary Program code:

#Recursive function 'decimalToBinary' accepts an argument value,
#to convert a decimal number to binary.
def decimalToBinary(value):
    # Base case: If the value is 0, return '0'.
    if value == 0:
        return '0'

    # Recursive case: Convert the quotient of value divided by 2 to binary,
    # concatenate it with the remainder of value divided by 2, and return the result.
    return decimalToBinary(value // 2) + str(value % 2)


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

# Convert the decimal number to binary
binary = decimalToBinary(decimal)

# Display the result
print(f"The binary equivalent of {decimal} is: {binary}")

 

Executed Output:

Enter a decimal number: 55
The binary equivalent of 55 is: 0110111

 

0 0

Discussions

Post the discussion to improve the above solution.