Reverse Polish in C/C++ For this assignment, you are to write a program, which w
ID: 3672494 • Letter: R
Question
Reverse Polish in C/C++
For this assignment, you are to write a program, which will calculate the results of Reverse Polish expressions that are provided by the user.
You must use a linked list to maintain the stack for this program (array implementations of the stack will not receive full credit).
You must handle the following situations (errors):
Too many operators (+ - / *)
Too many operands (doubles)
Division by zero
The program will take in a Polish expression that separates the operators and operands by a single space, and terminates the expression with an equals sign.
The program will continue to take and evaluate expressions until the user enters a zero (0) on a line by itself followed by a new line.
Your sample output should show the handling of all the error conditions as well as make use of all of the operators.
Sample IO: (note: formatting of output isn’t a critical issue)
Input Output
10 15 + = 25
10 15 - = -5
2.5 3.5 + = 6 (or 6.0)
10 0 / = Error: Division by zero
10 20 * / = Error: Too many operators
12 20 30 / = Error: Too many operands
-10 -30 - = 20
100 10 50 25 / * - -2 / = -40
Explanation / Answer
#include<iostream>
#include<cctype>
#include<stack>
using namespace std;
// returns the value when a specific operator
// operates on two operands
int eval(int op1, int op2, char operate) {
switch (operate) {
case '*': return op2 * op1;
case '/': return op2 / op1;
case '+': return op2 + op1;
case '-': return op2 - op1;
default : return 0;
}
}
// evaluates the postfix operation
// this module neither supports multiple digit integers
// nor looks for valid expression
// However it can be easily modified and some additional
// code can be added to overcome the above mentioned limitations
// it's a simple function which implements the basic logic to
// evaluate postfix operations using stack
int evalPostfix(char postfix[], int size) {
stack<int> s;
int i = 0;
char ch;
int val;
while (i < size) {
ch = postfix[i];
if (isdigit(ch)) {
// we saw an operand
// push the digit onto stack
s.push(ch-'0');
}
else {
// we saw an operator
// pop off the top two operands from the
// stack and evalute them using the current
// operator
int op1 = s.top();
s.pop();
int op2 = s.top();
s.pop();
val = eval(op1, op2, ch);
// push the value obtained after evaluating
// onto the stack
s.push(val);
}
i++;
}
return val;
}
// main
int main() {
char postfix[] = {'5','6','8','+','*','2','/'};
int size = sizeof(postfix);
int val = evalPostfix(postfix, size);
cout<<" Expression evaluates to "<<val;
cout<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.