9. Program to perform string reversal using stack?
Algorithm
Globally,Declare
variables top=-1,count=20,stack[30];and define MAX as 10.
Step
1:Start
Step
2:Declare array x[20].
Step
3:Input the string.
Step
4:Read the string,x.
Step
5:Call the function,push(x).
Step
6:Call the function,pop().
Step
7:Stop.
Function
push(char x[])
Step
1:Declare variable i=o.
Step
2:If top=MAX-1 then
2.1)Print Stack Overflow.
Step
3:Else
3.1)while(x[i]!=’\0’) repeat
steps a to d.
a)Increment top by
1.
b)Assign
stack[top]=x[i]
c)Increment i by
1.
d)Increment count
by 1.
3.2)End while.
Step
4:End if.
Step
5:Return.
Function
pop()
Step
1:Declare variable i.
Step
2:If top=-1 then
2.1)Print Stack Underflow.
Step
3:Else
3.1)while(i>0) repeat
steps a to c.
a)Print the
character at the top of the stack,stack[top].
b)Decrement i by
1.
c)Decrement top by
1.
3.2)End while.
Step
4:End if.
Step
5:Return.
Program
#include<stdio.h>
#include<conio.h>
#define
MAX 10
char
stack[30];
int
top=-1, count=20;
void
push(char c[]);
void pop();
void
main()
{
char x[20];
clrscr();
printf("Enter the string:\t");
gets(x);
push(x);
pop();
getch();
}
void
push(char x[])
{
int i=0;
if(top==MAX-1)
printf("overflow");
else
{
while(x[i]!='\0')
{
top++;
stack[top]=x[i];
i++;
count++;
}
}
}
void
pop()
{
int i;
if(top==-1)
{
printf("Stack Underflow");
}
else
{
i=count;
printf(“The reversed string is ”);
while(i>0)
{
printf("%c",stack[top]);
i--;
top--;
}
}
}
Output
Enter
the string PROGRAMMING
The
reversed string is GNIMMARGORP
No comments:
Post a Comment