-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix2.cpp
More file actions
107 lines (91 loc) · 1.88 KB
/
Copy pathpostfix2.cpp
File metadata and controls
107 lines (91 loc) · 1.88 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <ctype.h>
using namespace std;
/*
The program will evaluate a postfix expression that contains digits and operators.
The program tries to simulate the microprocessor execution stack or evaluation
of expression.
*/
//The class performing the evaluation
class Evaluation {
public:
int st[50];
int top;
char str[50];
Evaluation() {
top = -1;
}
//function to push the item
void push(int item) {
top++;
st[top] = item;
}
//function to pop an item
int pop() {
int item = st[top];
top--;
return item;
}
//function to perform the operation depending on the operator.
int operation(int a,int b,char opr) {
switch(opr) {
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
default: return 0;
}
}
int calculatePostfix();
};
void push(int item) {
top++;
st[top] = item;
}
//function to pop an item
int pop() {
int item = st[top];
top--;
return item;
}
int operation(int a,int b,char opr) {
switch(opr) {
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
default: return 0;
}
}
//This is the function that calculates the result of postfix expression.
int calculatePostfix() {
int index = 0;
while(str[index]!='\0') {
if(isdigit(str[index])) {
push(str[index]-'0');
}
else {
int x = pop();
int y = pop();
int result = operation(x,y,str[index]);
push(result);
}
index++;
}
return pop();
}
/*
main function that reads the postfix expression and that prints the result.
The input expression should be ending with a number
An example input expression would be:
123*+
Its output will be 7.
*/
int main() {
void clrscr();
Evaluation eval;
cout << "Enter the postfix: ";
//cin >> eval.str;
int result = eval.calculatePostfix();
cout << "the result is " << result;
}