Check sibling questions

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

Are ads bothering you?


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

Davneet Singh's photo - Teacher, Engineer, Marketer

Made by

Davneet Singh

Davneet Singh is a graduate from Indian Institute of Technology, Kanpur. He has been teaching from the past 12 years. He provides courses for Maths and Science at Teachoo.