Slip 24 - A) Write a ‘C’ program to read a postfix expression, evaluate it and display the result. (Use Dynamic Implementation of Stack)

Solution:

#include<stdio.h>
#include<conio.h>
#include<math.h>
char st[100];
int top=-1;
void push(char c)
{
top++;
st[top]=c;
}
char pop()
{
char c;
c=st[top];
top–;
return c;
}
int main()
{
int i,j,p,a,b,temp;
char s1[30];
clrscr();
printf(“\nEnter the Postfix Expr”);
gets(s1);
j=0;
for(i=0;s1[i]!=”;i++)
{
if(s1[i]<=’9′ && s1[i]>=’0′)
push(s1[i]-48);
else
{
a=pop();
b=pop();
switch(s1[i])
{
case ‘+’:
temp=b+a;
break;
case ‘-‘:
temp=b-a;
break;
case ‘/’: temp=b/a;
break;
case ‘*’:
temp=b*a;
break;
case ‘^’:
temp=pow(b,a);
break;
case ‘%’:
temp=b%a;
break;
}
push(temp);
}
}
j=pop();
printf(“Result is %d “,j);
getch();
return;
}

Post a Comment

0 Comments