Evaluate postfix sat
Fri Sep 01 2023 06:31:45 GMT+0000 (Coordinated Universal Time)
Saved by
@Astik
#include<stdio.h>
#include<string.h>
#include<conio.h>
char st[100], post[100], s[100];
int op[50];
int top = -1, id = 0,i,oid=-1 ;
void push(int x){
top ++ ;
st[top] = x ;
}
int pop (){
return st[top--];
}
int operand(char x){
return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');
}
int prec(char x){
if(x == '*' || x == '/') return 2 ;
else if(x == '+' || x == '-') return 1 ;
return 0 ;
}
int main(){
int n,a,b ;
printf("Enter the infix expression : ");
scanf("%s", s);
n = strlen(s);
push('(');
s[n] = ')';
for(i = 0 ; i <= n; i ++){
if(operand(s[i])){
post[id] = s[i];
id ++ ;
} else if(s[i] == '('){
push(s[i]);
} else if(s[i] != ')') {
while(prec(st[top]) >= prec(s[i])){
post[id ++] = pop();
}
push(s[i]);
} else{
while(st[top] != '('){
post[id ++] = pop();
}
pop();
}
}
for(i=0;i<=strlen(post);i++){
if(operand(post[i])){
op[++oid]=post[i]-'0';
}else{
a=op[oid];
oid--;
b=op[oid];
oid--;
if(post[i]=='+'){
op[++oid]=b+a;
}else if(post[i]=='-'){
op[++oid]=b-a;
}else if(post[i]=='*'){
op[++oid]=b*a;
}else{
op[++oid]=b/a;
}
op[++oid]=post[i]-'0';
}
}
printf("Answer is: %d",op[0]);
getch();
return 0;
}
content_copyCOPY
Comments