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

Question

(Print the digits in an integer reversely) Write a recursive function that displays an integer value reversely on the console using the following header:
         def reverseDisplay(value):
For example, invoking reverseDisplay(12345) displays 54321. Write a test program that prompts the user to enter an integer and displays its reversal.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Print the digits in an integer reversely Program code:

#Recursive function to display an integer value reversely.
def reverseDisplay(value):
    # Base case: If the value is 0, we have printed all the digits.
    if value == 0:
        return
    
    # Recursive case: Print the last digit of the value 
    #and recursively call reverseDisplay with the remaining
    #digits (excluding the last digit).
    last_digit = value % 10
    print(last_digit, end="")
    reverseDisplay(value // 10)


# Prompt and read the the user for input
value = int(input("Enter an integer number: "))

# Display the reversal of the input value
print("Reverse order:", end=" ")
reverseDisplay(value)
print()

Executed Output:

Enter an integer number: 12345
Reverse order: 54321

 

0 0

Discussions

Post the discussion to improve the above solution.