Write a program to print a string in reverse order.

Answer:

To print a string in reverse order, first insert each character of the string into a stack. Then, delete each element from the top of the stack and print the deleted element.

Code:

def push(rev,x):

rev.append(x)

return

def pop(rev):

if len(rev)==0:

print("Stack is empty")

else:

deleted_element=rev.pop()

return deleted_element

rev_stack=[]

input_string=input("Enter a string to be reversed: ")

for a in input_string:

push(rev_stack,a)

print("Reversed string: ")

for i in input_string:

x=pop(rev_stack)

print(x)

 

Output:

Enter a string to be reversed: welcome

Reversed string:

e

m

o

c

l

e

w

Slide23.JPG

Learn in your speed, with individual attention - Teachoo Maths 1-on-1 Class


Transcript

Write a program to print a string in reverse order. Answer: To print a string in reverse order, first insert each character of the string into a stack. Then, delete each element from the top of the stack and print the deleted element. Code: def push(rev,x): rev.append(x) return def pop(rev): if len(rev)==0: print("Stack is empty") else: deleted_element=rev.pop() return deleted_element rev_stack=[] input_string=input("Enter a string to be reversed: ") for a in input_string: push(rev_stack,a) print("Reversed string: ") for i in input_string: x=pop(rev_stack) print(x) Output: Enter a string to be reversed: welcome Reversed string: e m o c l e w

Ask a doubt
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 13 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.