-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEval_suffix_exp.c
More file actions
85 lines (85 loc) · 1.54 KB
/
Eval_suffix_exp.c
File metadata and controls
85 lines (85 loc) · 1.54 KB
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<string.h>
#include<stdlib.h>
#include<math.h>
//declare stack size as 100 to avoid segmentation fault
#define ss 100
//push function
void push(int item,int *top,int s[])
{
if(*top==ss-1)
{
printf("Stack Overflow\n");
return;
}
*top=*top+1;
s[*top]=item;
}
//pop function
int pop(int *top,int s[])
{
int item;
if(*top==-1)
return -1;
item=s[*top];
*top=*top-1;
return item;
}
//evaulate function
int eval(char postfix[])
{
int i,j,n,s[ss],op1,op2,res,top;
char symbol;
top=-1;
n=strlen(postfix);
for(i=0;i<n;i++)
{
symbol=postfix[i];
switch(symbol)
{
case '+': op2=pop(&top,s);
op1=pop(&top,s);
res=op1+op2;
push(res,&top,s);
break;
case '-': op2=pop(&top,s);
op1=pop(&top,s);
res=op1-op2;
push(res,&top,s);
break;
case '*': op2=pop(&top,s);
op1=pop(&top,s);
res=op1*op2;
push(res,&top,s);
break;
case '/': op2=pop(&top,s);
op1=pop(&top,s);
res=op1/op2;
push(res,&top,s);
break;
case '%': op2=pop(&top,s);
op1=pop(&top,s);
res=op1%op2;
push(res,&top,s);
break;
case '^':
case '$': op2=pop(&top,s);
op1=pop(&top,s);
res=(int)pow((double)op1,(double)op2);
push(res,&top,s);
break;
default: push(symbol-'0',&top,s);
}
}
return(pop(&top,s));
}
//main function
void main()
{
char postfix[ss];
int res;
printf("Enter the postfix expression:\n");
scanf("%s",postfix);
res=eval(postfix);
printf("The solution of the postfix expression is \n%d\n",res);
}