-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfixeval.c
111 lines (82 loc) · 1.83 KB
/
postfixeval.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdio.h>
#include <ctype.h>
#define MAXSTACK 100
#define POSTFIXSIZE 100
int stack[MAXSTACK];
int top = -1;
void push(int item)
{
if (top >= MAXSTACK - 1) {
printf("stack over flow");
return;
}
else {
top = top + 1;
stack[top] = item;
}
}
int pop()
{
int item;
if (top < 0) {
printf("stack under flow");
}
else {
item = stack[top];
top = top - 1;
return item;
}
}
void EvalPostfix(char postfix[])
{
int i;
char ch;
int val;
int A, B;
for (i = 0; postfix[i] != '@'; i++) {
ch = postfix[i];
if (isdigit(ch)) {
push(ch - '0');
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
A = pop();
B = pop();
switch (ch)
{
case '*':
val = B * A;
break;
case '/':
val = B / A;
break;
case '+':
val = B + A;
break;
case '-':
val = B - A;
break;
default:
printf("Invalid operator\n");
//exit(1);
}
push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}
int main()
{
int i;
char postfix[POSTFIXSIZE];
printf("ASSUMPTION: There are only four operators(*, /, +, -) in an expression and operand is single digit only.\n");
printf(" \nEnter postfix expression,\npress right parenthesis '$' for end expression : ");
for (i = 0; i <= POSTFIXSIZE - 1; i++) {
scanf("%c", &postfix[i]);
if (postfix[i] == '@')
{
break;
}
}
EvalPostfix(postfix);
return 0;
}