In class, I had shown you how stacks are used to evaluate expressions in the pos
ID: 3538604 • Letter: I
Question
In class, I had shown you how stacks are used to evaluate expressions in the postfix form. Your task is to program a calculator that uses a stack. These calculators use "postfix" notation or "Reverse Polish notation (RPN)" for their mathematical expressions.
For example, 5 - 2 is instead written 5 2 - and 5 - (2 + 1) written 5 2 1 + -
The way this works is as follows:
If a number is typed, push it on the stack.
If an operation is typed, depending on the operation, pop off zero or more numbers from the stack, perform the operation, and possibly push the result(s) back on the stack.
It is upto you whether you want the user to enter the expression in infix form or in postfix form. If the user enters in infix form, then you have to convert it to postfix form before evaluating it using the stack. The interface allows you to enter one element at a time, and depending on whether the element was an operand or an operator, performs the necessary step.
*Note : I will be using just binary operators when entering an expression for evaluation.
Explanation / Answer
#include <iostream> #include <vector> using namespace std; vector<int> integerarray; void evaluate(char c) { int denominator=integerarray.back(); integerarray.pop_back(); int numerator=integerarray.back(); integerarray.pop_back(); if (c=='+') { integerarray.push_back((int)numerator+(int)denominator); } else if(c=='-') { integerarray.push_back((int)numerator-(int)denominator); } else if(c=='*') { integerarray.push_back((int)numerator*(int)denominator); } else if(c=='/') { integerarray.push_back((int)numerator/(int)denominator); } } int main() { char c; cin>>c; int k=0,number=0; while(c!=' ') { if(c>=48 && c<58) { number=number*10+c-48; k=1; } else if(c==' ') { if(k==1) { integerarray.push_back(number); number=0; k=0; } } else { evaluate(c); } cin>>noskipws>>c; } cout << (int)integerarray.back()<< endl; return 0; } #include <iostream> #include <vector> using namespace std; vector<int> integerarray; void evaluate(char c) { int denominator=integerarray.back(); integerarray.pop_back(); int numerator=integerarray.back(); integerarray.pop_back(); if (c=='+') { integerarray.push_back((int)numerator+(int)denominator); } else if(c=='-') { integerarray.push_back((int)numerator-(int)denominator); } else if(c=='*') { integerarray.push_back((int)numerator*(int)denominator); } else if(c=='/') { integerarray.push_back((int)numerator/(int)denominator); } } int main() { char c; cin>>c; int k=0,number=0; while(c!=' ') { if(c>=48 && c<58) { number=number*10+c-48; k=1; } else if(c==' ') { if(k==1) { integerarray.push_back(number); number=0; k=0; } } else { evaluate(c); } cin>>noskipws>>c; } cout << (int)integerarray.back()<< endl; return 0; } Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.