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

Learn Intergation from Davneet Sir - Live lectures starting soon!


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 - 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 12 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.