-
Notifications
You must be signed in to change notification settings - Fork 1
/
3_12_Evaluvation.c
123 lines (107 loc) · 2.64 KB
/
3_12_Evaluvation.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
112
113
114
115
116
117
118
119
120
121
122
123
#include <stdio.h>
#include <string.h>
#define MAX 10
char stk[MAX];
int top = -1;
void push(char x) {
top++;
stk[top] = x;
}
char pop() {
char y = stk[top];
top--;
return y;
}
int precedence(char k) {
if (k == '^') {
return 3;
} else if (k == '*' || k == '/') {
return 2;
} else if (k == '+' || k == '-') {
return 1;
} else {
return 0;
}
}
char conversion() {
char infix[MAX], postfix[MAX];
printf("Enter infix expression: ");
scanf("%s", infix);
push('#');
int i = 0, j = 0;
char temp,k;
while (infix[i] != '\0') {
temp = infix[i];
switch (temp) {
case '(':
push(temp);
break;
case ')':
k = pop();
while (k != '(') {
postfix[j] = k;
j++;
k = pop();
}
break;
case '^':
case '*':
case '/':
case '+':
case '-':
while (precedence(stk[top]) >= precedence(temp)) {
postfix[j] = pop();
j++;
}
push(temp);
break;
default:
postfix[j] = temp;
j++;
}
i++;
}
while (top > 0) {
postfix[j] = pop();
j++;
}
postfix[j] = '\0';
puts("Postfix expression:");
puts(postfix);
int resultstk[MAX];
int resTop = -1;
int operand1, operand2;
i = 0;
while (postfix[i] != '\0') {
if (isdigit(postfix[i])) {
push(postfix[i] - '0'); // Convert char digit to int and push to stack
} else {
operand2 = pop();
operand1 = pop();
switch (postfix[i]) {
case '^':
push(pow(operand1, operand2));
break;
case '*':
push(operand1 * operand2);
break;
case '/':
push(operand1 / operand2);
break;
case '+':
push(operand1 + operand2);
break;
case '-':
push(operand1 - operand2);
break;
}
}
i++;
}
int evaluationResult = pop();
printf("Expression Evaluation Result: %d\n", evaluationResult);
}
int main() {
conversion();
return 0;
}