-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixEvaluation.c
134 lines (99 loc) · 2.75 KB
/
InfixEvaluation.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
126
127
128
129
130
131
132
133
134
// Created by Brett Fazio
// Evaluation of infix expression without the use of any objects/classes
// Just does integers, but can easily do doubles just by changing my v[]
// to type double.
#include <stdio.h>
#define SIZE 100
int isOperation(char in);
int modify(int a, int b, int op);
int getNumeric(char in);
int main() {
printf("Enter the infix expression:\n");
char expression[SIZE];
scanf("%s", expression);
int length = 1;
int operations = 0;
int values = 0;
for (int i = 1; i < SIZE; i++) {
char current = expression[i];
if (isOperation(current) != isOperation(expression[i-1])) {
length++;
}
if (isOperation(current) == 1) {
operations++;
}
}
values = length - operations;
int v[values];
int o[operations];
int vpointer = -1;
int opointer = -1;
for (int i = 0; i < SIZE; i++) {
if (expression[i] == '\0') {
break;
}
if (isOperation(expression[i])) {
int numeric = getNumeric(expression[i]);
while (opointer >= 0 && numeric < o[opointer]) {
v[vpointer-1] = modify(v[vpointer-1], v[vpointer], o[opointer]);
v[vpointer] = 0;
o[opointer] = 0;
vpointer--;
opointer--;
}
opointer++;
o[opointer] = numeric;
}else {
int construct = 0;
construct = (int)(expression[i]-'0');
while (i+1 < SIZE && expression[i+1] != '\0' && isOperation(expression[i+1]) == 0){
construct *= 10;
i++;
construct += (int)(expression[i]-'0');
}
vpointer++;
v[vpointer] = construct;
}
}
while (opointer >= 0) {
v[vpointer-1] = modify(v[vpointer-1], v[vpointer], o[opointer]);
v[vpointer] = 0;
o[opointer] = 0;
vpointer--;
opointer--;
}
printf("Evaluation = %d\n", v[0]);
}
int getNumeric(char in) {
if (in == '+') {
return 1;
}
if (in == '-') {
return 2;
}
if (in == '*') {
return 3;
}
if (in == '/') {
return 4;
}
return 0;
}
int modify(int a, int b, int op) {
if (op == 1) {
return a + b;
}
if (op == 2) {
return a - b;
}
if (op == 3) {
return a * b;
}
if (op == 4) {
return a / b;
}
return 0;
}
int isOperation(char in) {
return (in == '+' || in == '-' || in == '/' || in == '*') ? 1 : 0;
}