-
Notifications
You must be signed in to change notification settings - Fork 1
/
18_postfix_evaluation.c
83 lines (76 loc) · 1.02 KB
/
18_postfix_evaluation.c
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<stdio.h>
#include<stdlib.h>
double stack[100];
int top=-1,maxsize=100;
void push(double n)
{
if(top == maxsize )
printf(" StackOverflow \n");
else
{
top++;
stack[top]=n;
}
}
double pop()
{
if(top==-1)
{
return 0;
}
else
{
top--;
return stack[top+1];
}
}
int main()
{
char postfix[100];
double temp1,temp2;
int i,valid=1;
printf(" Enter Postfix Expression : ");
scanf("%s",postfix);
for(i=0;postfix[i]!='\0' && valid;i++)
{
char c=postfix[i];
if(isdigit(c))
push(c-'0');
else
{
temp1=pop();
temp2=pop();
if(top<-1)
valid=0;
switch(c)
{
case '+':
push(temp2+temp1);
break;
case '-':
push(temp2-temp1);
break;
case '*':
push(temp2*temp1);
break;
case '/':
if(temp2==0)
{
valid=0;
break;
}
push(temp2/temp1);
break;
default:
valid=0;
break;
}
}
}
if(top!=0)
valid=0;
if(valid)
printf(" Result : %.2f\n",pop());
else
printf(" Invalid Expression ");
}