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

Question

(Print the characters in a string reversely) Write a recursive function that displays a string reversely on the console using the following header:
            def reverseDisplay(value):
For example, reverseDisplay("abcd") displays dcba. Write a test program that prompts the user to enter a string and displays its reversal.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Print the characters in a string reversely Program code:

# Recursive function 'reverseDisplay' to display a string reversely.
def reverseDisplay(value):
    # Base case: If the length of the value is 0, 
    #printed all the characters.
    if len(value) == 0:
        return
    
    # Recursive case: Print the last character of the value
    #and recursively call reverseDisplay
    # with the remaining characters (excluding the last character).
    last_character = value[-1]
    print(last_character, end="")
    reverseDisplay(value[:-1])


# Prompt the user for input
value = input("Enter a string: ")

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

 

Executed Output:

Enter a string: abcd
Reverse string order: dcba

 

0 0

Discussions

Post the discussion to improve the above solution.