-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpref_eval.c
53 lines (48 loc) · 1.24 KB
/
pref_eval.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
#include <stdio.h>
#include <string.h>
#include <math.h>
char prefix[100];
double stack[100];
int top = -1;
void push(double number) {
top++;
stack[top] = number;
}
double pop() {
double del_element;
del_element = stack[top];
top--;
return del_element;
}
int is_operator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');
}
void main() {
char operand;
double x, y, result;
printf("Enter the prefix expression: ");
fgets(prefix, 99, stdin);
prefix[strlen(prefix) - 1] = '\0';
for (int i = strlen(prefix) - 1; i >= 0; i--) {
if (is_operator(prefix[i])) {
operand = prefix[i];
x = pop();
y = pop();
if (operand == '+') {
result = x + y;
} else if (operand == '-') {
result = x - y;
} else if (operand == '*') {
result = x * y;
} else if (operand == '/') {
result = x / y;
} else if (operand == '^') {
result = pow(x, y);
}
push(result);
} else {
push((double)(prefix[i] - '0'));
}
}
printf("The evaluated expression is: %f", pop());
}