-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpostfix_evaluation.c
82 lines (78 loc) · 1.18 KB
/
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>
#define SIZE 100
#include <math.h>
#include <stdlib.h>
/*my own stack*/
int Stack[SIZE];
int top = -1;
int isEmpty()
{
return top == -1;
}
void push(int item)
{
Stack[++top] = item;
}
int pop()
{
if(isEmpty())
{
printf("STACK UNDERFLOW\n");
exit(0);
}
int temp = Stack[top];
top--;
return temp;
}
int evalPostfix(char *exp)
{
int i = 0;
char str[50];
int j = 0;
//parsing
while (exp[i] != '\0')
{
if (exp[i] >= '0' && exp[i] <= '9')
{
push(exp[i] - '0');
}
else //operator
{
if(isEmpty())
{
return -1;
}
int b = pop();
int a = pop();
int result = 0;
switch (exp[i])
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '/':
result = a / b;
break;
case '*':
result = a * b;
break;
case '^':
result = (int)pow(a, b);
}
push(result);
}
i++;
}
return Stack[top];
}
int main()
{
char str[SIZE];
printf("Enter the postfix expression\n");
scanf("%s", str);
int result = evalPostfix(str);
printf("RESULT: %d\n", result);
}