forked from raolokesh126/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluationpostfix.cpp
100 lines (96 loc) · 1.94 KB
/
evaluationpostfix.cpp
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
#include<iostream>
#include<cstdio>
#include<cctype>
#include<cmath>
#include<cstdlib>
#define MAX 100
using namespace std;
struct postfix
{
int stack[MAX];
int top,n;
char *s;
}p;
void init_post()
{
p.top=-1;
}
void init_exp(char *str)
{
p.s=str;
}
void push(int number)
{
p.top++;
p.stack[p.top]=number;
}
int pop()
{
int number=p.stack[p.top];
p.top--;
return number;
}
void calculate()
{
int n1, n2, x;
while(*(p.s))
{
if(*(p.s)==' ' || *(p.s)==' ')
{
p.s++;
continue;
}
if(isdigit(*(p.s)))
{
p.n=*(p.s)-'0';
push(p.n);
}
else
{
n1=pop();
n2=pop();
switch(*(p.s))
{
case '+':
x=n2+n1 ;
break;
case '-':
x=n2-n1 ;
break;
case '*':
x=n2*n1 ;
break;
case '/':
x=n2/n1 ;
break;
case '%':
x=n2%n1 ;
break;
case '^':
x=(int)pow(n2,n1) ;
break;
default:
cout<<"Invalid operator !!\n" ;
exit(1);
}
push(x);
}
p.s++;
}
}
void disp_result()
{
p.n=pop();
cout<<"\nResult = "<<p.n;
}
int main()
{
char exp[MAX];
init_post();
cout<<"Enter the postfix formed expression : ";
cin>>exp;
init_exp(exp);
calculate();
disp_result();
return 0;
}