forked from ashvish183/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix_evaluation.cpp
60 lines (56 loc) · 1.32 KB
/
postfix_evaluation.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
//Program to postfix evaluation using stack data structure
#include<bits/stdc++.h>
using namespace std;
float scanNum(char ch) {
int value;
value = ch;
return float(value-'0');
}
int isOperator(char ch) {
if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
return 1;
return -1;
}
int isOperand(char ch) {
if(ch >= '0' && ch <= '9')
return 1;
return -1;
}
float operation(int a, int b, char op) {
if(op == '+')
return b+a;
else if(op == '-')
return b-a;
else if(op == '*')
return b*a;
else if(op == '/')
return b/a;
else if(op == '^')
return pow(b,a);
else
return INT_MIN;
}
float postfixEval(string postfix) {
int a, b;
stack<float> stk;
string::iterator it;
for(it=postfix.begin(); it!=postfix.end(); it++) {
if(isOperator(*it) != -1) {
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(operation(a, b, *it));
}else if(isOperand(*it) > 0) {
stk.push(scanNum(*it));
}
}
return stk.top();
}
int main() {
string exp;
cout<<"Enter postfix expression : ";
cin>>exp;
cout << "The value of given expression is : "<<postfixEval(exp);
return 0;
}