-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path5.Postfix_Evaluation.c
More file actions
52 lines (51 loc) · 1.44 KB
/
5.Postfix_Evaluation.c
File metadata and controls
52 lines (51 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*e are pushing the operands or the numbers into the stack here.
In infix to postfix conversion we pushed the operators into the stack.
So here data type of stk will be int whereas in the previous case it was char
When an operator is encountered pop 2 numbers,find their result using the operator and push the
result back into the stack*/
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int stk[MAX],top=-1;
char pf[MAX];
int pop(){
return stk[top--];
}
void push(int x){
stk[++top]=x;
}
int evaluate(char op){
int a=pop(),b=pop();
switch(op){
case '+': return b+a;
case '-': return b-a;
case '*': return b*a;
case '/': return b/a;
case '^': return b^a;
case '%': return b%a;
}
}
int isoperator(char x){
if(x=='+'||x=='-'||x=='*'||x=='/'||x=='%'||x=='^')
return 1;
return 0;
}
int main(){
int i,d;
printf("\nEnter the postfix expression to be evaluated\n");
scanf("%s",pf);
for(i=0;pf[i]!='\0';i++){
if(pf[i]>='0'&&pf[i]<='9')
push(pf[i]-48);
else if(isoperator(pf[i]))
push(evaluate(pf[i]));//Push the result into the stack
else{
printf("\nNot a valid expression\n");
return 0;
}
}
if(top==0)
printf("\nThe result of the postfix expression is %d\n",stk[top]);
else
printf("\nNot a valid postfix expression\n");
}