There are some mistakes in this
First one is while(str[index]!='#')
Change '#' into '\0'
The second one is operation function, In the code given above you are performing operations between first popped and second popped element but you need to perform operation between second popped and first popped(To be presice According to given solution if 43- is postfix expression operation is done like 3-4=-1 but correct one is 4-3=1)
so change a little here :
else {
int x = pop();
int y = pop();
int result = operation(x,y,str[index]);
push(result);
}
Do a small change as operation(y,x,str[index])
Example 4325*-+
According to code we get 11 as answer I think but correct answer is -3(I have checked it in internet)
We will get that answer if we make the changes suggested by me....
The total code is as follows:
#include<iostream>
using namespace std;
class Evaluation {
public:
int st[50];
int top;
char str[50];
Evaluation() {
top = -1;
}
void push(int val) {
top++;
st[top] = val;
}
int pop() {
int val = st[top];
top--;
return val;
}
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();
};
int Evaluation::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(y,x,str[index]);
push(result);
}
index++;
}
return pop();
}
int main() {
Evaluation eval;
cout << "Enter the postfix: ";
cin >> eval.str;
int result = eval.calculatePostfix();
cout << "The result is " << result;
return 0;
}
P.S.Please correct me if I am wrong