This lab consists of two parts: Postfix calculator Algorithm Analysis problems I
ID: 3810902 • Letter: T
Question
This lab consists of two parts: Postfix calculator Algorithm Analysis problems In this lab you are going to write reverse postfix calculator using a stack. Postfix notation and is parenthesis-free as long as operator arities are fixed. In postfix notation the operators follow their operands; for instance, to add 3 and 4, one would write "3 4 rather than "3 4". If there are multiple operations, the operator is given immediately after its second operand; so the expression written "3 4 5" in conventional notation would be written "3 4 5 in postfix: first subtract 4 from 3, then add 5 to that. An advantage of postfix is that it eliminates the need for parentheses that are required by infix. While "3 4* 5" can also be written "3 (4 50", that means something quite different from "(3-4) 5" In postfix, the former could be written "3 4 5 which unambiguously means "3 (4 5 11 which reduces to "3 20 11 the latter could be written "3 4 5*" (or 5 3 4 if you wish to keep similar formatting), which unambiguously means "(3 4 5 *11 Standard expression (infix notation) Postfix Notation Value 10 (6 2.3 10 62+ 3 2
Explanation / Answer
Here is the code for you:
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
bool isOperator(char ch)
{
if (ch=='+' || 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;
case '%':
ans = op2 % op1;
break;
}
return ans;
}
int main()
{
string post;
char buffer[15];
int i,op1, op2, len, j, x, numOfExpressions;
stack<int> s;
size_t bufSize = 256;
while(true)
{
cout << "Type in a postfix expression or stop to stop: ";
getline(cin, post);
if(post.compare("stop") == 0)
return 0;
//for(int k = 0; k < numOfExpressions; k++)
{
//fgets(post, 250, fin);
//fin.getline ( post, 256, ' ' );
len = post.length(); //strlen(post);
j = 0;
for(i=0; i<len;i++){
if(post[i]>='0' && post[i]<='9'){
buffer[j++] = post[i];
}
else if(post[i]==' '){
if(j>0){
buffer[j] = '';
x = atoi(buffer);
s.push(x);
j = 0;
}
}
else if(isOperator(post[i])){
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(performOperation(op1, op2, post[i]));
}
}
printf("%s = %d ", post.c_str(), s.top());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.