-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefix-evaluation.c
64 lines (57 loc) · 1.26 KB
/
prefix-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
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define MAX 50
int top = -1;
char stack[MAX];
char prefix[MAX];
int x[MAX];
void push(int item){
if(top==MAX-1){
printf("Stack Overflow\n");
return;
}
stack[++top]=item;
}
int pop(){
if(top==-1){
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int prefix_evaluation (){
int i=0,a,b;
strrev(prefix);
while(prefix[i] !='\0'){
if(isalpha(prefix[i])){
push(x[strlen(prefix)-i-1]);
}
else{
b=pop();
a=pop();
switch(prefix[i]){
case '+': push(a+b); break;
case '-': push(a-b); break;
case '*': push(a*b); break;
case '/': push(a/b); break;
}
}
i++;
}
return pop();
}
int main(){
printf("Enter the prefix expression: ");
gets(prefix);
int i=0;
while (prefix[i] !='\0'){
if(isalpha(prefix[i])){
printf("Enter the value of %c: ", prefix[i]);
scanf("%d", &x[i]);
}
i++;
}
printf("The result is: %d\n", prefix_evaluation());
return 0;
}