-
Notifications
You must be signed in to change notification settings - Fork 0
/
postfix_evaluation_using_stacks.c
85 lines (61 loc) · 1.39 KB
/
postfix_evaluation_using_stacks.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
#include<stdio.h>
#include<math.h>
int top=-1;
void push(int ele, int ar[], int size){
//printf("top is %d\n", top);
if(top>=(size-1)){
printf("stack overflow\n");
}
else{
top=top+1;
ar[top]=ele;
//printf("arr[top] is %d\n",ar[top]);
}
}
int pop(int ar[]){
if(top==-1){
printf("stack underflow\n");
}
else{
return ar[top--];
}
}
int evaluate(char ar[], int len){
char stack[len];
for(int i=0;i<len;i++){
if(ar[i]=='*' || ar[i]=='/' || ar[i]=='-' || ar[i]=='+' || ar[i]=='$'){
int b= pop(stack)-'0';
int a=pop(stack)-'0';
int c;
//printf("a is %d and b is %d \n",a,b);
if(ar[i]=='*')
c=a*b;
else if(ar[i]=='/')
c=a/b;
else if(ar[i]=='-')
c=a-b;
else if(ar[i]=='+')
c=a+b;
else
c=pow(a,b);
//printf("val of c is %d\n",c);
char result = c+'0';
push(result,stack,len);
}
else{
push(ar[i],stack,len);
}
}
int ans= pop(stack)-'0';
return ans;
}
void main(){
printf("enter the length of the postfix expression\n");
int len;
scanf("%d",&len);
printf("Enter postfix expression: ");
char expression[len];
scanf("%s",&expression);
int ans= evaluate(expression, len);
printf("after evaluation we get %d ", ans);
}