Stack Program #5
19. Write a program for evaluation of post-fix expression using Stack.
#include<stdio.h>
#define N 50
char s[N];
int top=-1;
void push(int);
int pop();
int perform(int oprand1,int oprand2,char temp);
void main()
{
int i=0,value=0,oprand1,oprand2,x,result,j;
char postfix[50],temp;
printf("Enter the postfix expression:\n");
scanf("%s",postfix);
temp=postfix[i];
while(temp!='\0')
{
if(temp>='0' && temp<='9')
{
push(temp-'0');
}
else
{
oprand2=pop();
oprand1=pop();
value=perform(oprand1,oprand2,temp);
push(value);
printf ("%c\t", temp);
}
printf("\nThe stack is\n");
for (j=top;j>=0;j--)
{
printf ("%d\n", s[j]);
}
i++;
temp=postfix[i];
}
result=pop();
printf("Evaluation of postfix exp. is %d\n",result);
}
void push(int x)
{
if(top>=N-1)
{
printf("STACK OVERFLOW\n");
}
else
{
top++;
s[top]=x;
}
}
int pop()
{
if(top==-1)
{
printf("STACK UNDERFLOW\n");
return('\0');
}
else
{
top=top-1;
return(s[top+1]);
}
}
int perform(int oprand1,int oprand2,char temp)
{
int j=1,ans;
if(temp=='+')
{
return(oprand1+oprand2);
}
else if(temp=='-')
{
return(oprand1-oprand2);
}
else if(temp=='*')
{
return(oprand1*oprand2);
}
else if(temp=='/')
{
return(oprand1/oprand2);
}
else if(temp=='^' || temp=='$')
{
for(j=1;j<=oprand2;j++)
{
ans=oprand1*ans;
}
return(ans);
}
}
OR
#include<stdio.h>#include<ctype.h>
#include<math.h>
#define N 50
char s[N];
int top=-1;
void push(int);
int pop();
int perform(int oprand1,int oprand2,char temp);
void main()
{
int i=0,value=0,oprand1,oprand2,x,result;
char postfix[50],temp;
printf("Enter the postfix expression:\n");
scanf("%s",postfix);
temp=postfix[i];
while(temp!='\0')
{
if(isdigit(temp))
{
push(temp-'0');
}
else
{
oprand2=pop();
oprand1=pop();
value=perform(oprand1,oprand2,temp);
push(value);
}
i++;
temp=postfix[i];
}
result=pop();
printf("Evaluation of postfix exp. is %d\n",result);
}
void push(int x)
{
if(top>=N-1)
{
printf("STACK OVERFLOW\n");
}
else
{
top++;
s[top]=x;
}
}
int pop()
{
if(top==-1)
{
printf("STACK UNDERFLOW\n");
return('\0');
}
else
{
top=top-1;
return(s[top+1]);
}
}
int perform(int oprand1,int oprand2,char temp)
{
int j=1,ans;
if(temp=='+')
{
return(oprand1+oprand2);
}
else if(temp=='-')
{
return(oprand1-oprand2);
}
else if(temp=='*')
{
return(oprand1*oprand2);
}
else if(temp=='/')
{
return(oprand1/oprand2);
}
else if(temp=='^' || temp=='$')
{
for(j=1;j<=oprand2;j++)
{
ans=oprand1*ans;
}
return(ans);
}
}
Output
- Enter the postfix expression:
752+*411+/-
The stack is
7
The stack is
5
7
The stack is
2
5
7
+
The stack is
7
7
*
The stack is
49
The stack is
4
49
The stack is
1
4
49
The stack is
1
1
4
49
+
The stack is
2
4
49
/
The stack is
2
49
-
The stack is
47
Evaluation of postfix exp. is 47
OR
Output
- Enter the postfix expression:
752+*411+/-
Evaluation of postfix exp. is 47
Comments
Post a Comment