-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfixToPostfix.c
125 lines (112 loc) · 2.97 KB
/
infixToPostfix.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
124
125
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<math.h> // For pow function
char infix[100], postfix[100];
int priority(char symbol) {
switch(symbol) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
char associativity(char symbol) {
if(symbol == '^') {
return 'R';
}
return 'L';
}
void infixtopost() {
char stk[100];
int i=0, j=0, top=-1;
char symbol;
for(int i = 0; infix[i] != '\0'; i++) {
symbol = infix[i];
if(isalnum(symbol)) {
postfix[j++] = symbol;
} else {
if(symbol == '(') {
stk[++top] = symbol;
} else if(symbol == ')') {
while(top != -1 && stk[top] != '(') {
postfix[j++] = stk[top--];
}
top--;
} else {
while(top != -1 && (priority(symbol) < priority(stk[top]) || ((priority(symbol) == priority(stk[top])) && associativity(stk[top]) == 'L'))) {
postfix[j++] = stk[top--];
}
stk[++top] = symbol;
}
}
}
while(top != -1) {
postfix[j++] = stk[top--];
}
postfix[j] = '\0';
printf("%s\n", postfix);
}
void evaluation() {
float st[100];
int top = -1;
for(int i = 0; i < strlen(postfix); i++) {
char symbol = postfix[i];
if(isalnum(symbol)) {
st[++top] = symbol - '0'; // Convert char to int
} else {
float op2 = st[top--];
float op1 = st[top--];
float res;
switch(symbol) {
case '+':
res = op1 + op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
res = op1 / op2;
break;
case '^':
res = pow(op1, op2); // Exponentiation using pow function
break;
}
st[++top] = res;
}
}
printf("%f\n", st[top--]);
}
int main() {
int choice;
while(1) {
printf("enter the choice\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("enter the expression\n");
scanf("%s", infix);
break;
case 2:
infixtopost();
// printf("%s\n", postfix);
break;
case 3:
evaluation();
break;
default:
break;
}
}
return 0;
}