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:20 | ISBN:978013274719 | Edition: 6

Question

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Decimal to hex Conversion Program Code:

#Recursive function 'decimalToHex' accepts an integer parameter, value
#to convert a decimal number to hexadecimal.
def decimalToHex(value):
    # Define a dictionary for hexadecimal digits
    hex_digits = "0123456789ABCDEF"

    # Base case: If the value is less than or equal to 15, 
    #return the corresponding hexadecimal digit
    if value <= 15:
        return hex_digits[value]

    # Recursive case: Convert the quotient of value divided by 16 to hexadecimal,
    # concatenate it with the remainder of value divided by 16, and return the result.
    return decimalToHex(value // 16) + hex_digits[value % 16]


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

# Convert the decimal number to hexadecimal
hexadecimal = decimalToHex(decimal)

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

 

Executed Output:

Enter a decimal number: 255
The hexadecimal equivalent of 255 is: FF

 

0 0

Discussions

Post the discussion to improve the above solution.