In C++ write a program that uses a stack to evaluate a postfix expression. The a
ID: 3683818 • Letter: I
Question
In C++ write a program that uses a stack to evaluate a postfix expression. The algorithm for the evaluation is as follows:
Read first symbol in input
While(There are more symbols to process)
{
If (symbol is an operand)
{
Push symbol onto the stack
}
Else //Symbol is an operation
{
Pop stack and save as operand2
Pop Stack and save as operand1
Perform operand1 symbol operand2
Push result onto stack
}
}
Pop stack and display as answer
-You can assume the user inputs a correct postfix expression.
-Read each input character separately using cin.get().
-You can assume the user will only input single digit operands.
-Use a switch statement to determine the correct operation.
-You can assume the only operations are (+,-,*,/).
Explanation / Answer
/*
* Postfix Evaluation
* Language: C++
*/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <stack>
#include <string.h>
using namespace std;
bool isOperator(char ch)
{
if (ch=='+' || ch=='-' || ch=='*' || ch=='/')
return true;
else
return false;
}
int performOperation(int op1, int op2, char op)
{
int ans;
switch(op){
case '+':
ans = op2 + op1;
break;
case '-':
ans = op2 - op1;
break;
case '*':
ans = op2 * op1;
break;
case '/':
ans = op2 / op1;
break;
}
return ans;
}
int main()
{
char exp[1000] = "34*", buffer[15];
char ch;
int i,op1, op2, len, j, x;
stack<int> s;
printf("Enter a Postfix Expression: ( e.g. 34* ) ");
cin.get(ch);
i = 0;
while(ch!=' ')
{
exp[i++] = ch;
cin.get(ch);
}
exp[i] = '';
printf("You entered Postfix %s ", exp);
len = strlen(exp);
j = 0;
for(i=0; i<len;i++){
cout<<"character = "<<exp[i]<<endl;
if(exp[i]>='0' && exp[i]<='9'){
s.push(exp[i]-'0');
}
else if(isOperator(exp[i])){
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(performOperation(op1, op2, exp[i]));
}
}
printf(" Answer is %d ", s.top());
return 0;
}