Question

In: Computer Science

For this assignment, implement a simple stack calculator which can compute an infix expression. It should...

For this assignment, implement a simple stack calculator which can compute an infix expression. It should take in a string containing an infix expression, compute the result, and print it out. It should handle operators +, -, *, / and parenthesis.

Your program must have two main steps -- first convert the expression to postfix, and then compute the result using the algorithms discussed in class and textbook. These algorithms require that you use a stack. You must implement your own stack, you may not use a library that implements a stack. No credit will be given if you don't implement your own stack.

Although your textbook contains implementations of a stack, I encourage you to try and implement your own stack, using the textbook as a reference if you need it. You can keep your stack simple if you wish -- e.g. it doesn’t need to be templated, it can just hold a simple data type like char. Additionally, it doesn’t need to handle error conditions because we are guaranteed a string containing a syntactically correct infix expression. You may implement either an array-based stack or a link-based stack.

To keep things simple, you may make the following assumptions:

- there are no spaces or other whitespace in the string

- all the operands are single digits

- the result of every operation is a single digit. For example, 2+3 is allowed because the result is 5. 5*3 is not allowed because the result is 15, which is two digits. 5+3+4 is not allowed because even though the first operation is 8, a single digit, the result of the second operation is 12, two digits. 5+3-4 is allowed because the result of the first operation is 8, and the result of the second operation is 4

- any string entered contains a valid, syntactically correct infix expression with balanced parenthesis (if any)

Conversion between int and char

The expression contains both char and int data, because each operator is a char and each operand is a digit. The easiest way to handle this is to implement a stack which supports char data. Since we know all our operands are single digits, we can simply push the character representing the digit onto the stack. Note this character will be the ASCII value of the character, not the integer value! As an example, the character '7' is ASCII value 55, '8' is 56, etc. If you need the actual integer value of the character, in this case 7, there is a convenient way to determine it. You can subtract the ASCII value of zero, '0' from the character. For example,, the following code will store 7 in i:

char c = '7';

int i = c - '0';

To get the character back, you can add '0' to an integer.

Extra Credit

For up to 10% extra credit, modify your program to remove the assumption that the string contains a valid, syntactically correct infix expression. It should compute the value if the string is valid, and gracefully handle an invalid string.

Solutions

Expert Solution

#include<cstdio>

#include <cstdlib>

#include <cstring>

#include <stack>

#include <cctype>

using namespace std;

bool error;

// returns true if op2 has lower or equal priority than op1, false otherwise

bool hasLowerPriority(char op1, char op2) {

switch (op1) {

case '(': return false;

case '-': return op2 == '-';

case '+': return op2 == '-' || op2 == '+';

case '*': return op2 != '/';

case '/': return true;

default : error = true; return false;

}

}

stack < char > operators;

stack < int > operands;

// perform the operation 'op' on the two operands on top of the stack

void operation(char op) {

if(operands.size() < 2) {

error = true; return;

}

int op2 = operands.top(); operands.pop();

int op1 = operands.top(); operands.pop();

switch(op) {

case '+': operands.push(op1 + op2); break;

case '-': operands.push(op1 - op2); break;

case '*': operands.push(op1 * op2); break;

case '/': operands.push(op1 / op2); break;

default : error = true; return;

}

}

int main() {

char exp[1000], *p;

int len;

printf("\t\t\t\tCALCULATOR\n");

while(true) {

printf("\nEnter an expression (. to exit):\n");

scanf("%[^\n]%*c", exp);

if(exp[0] == '.') break;

len = strlen(exp);

if(len == 0) { getchar(); continue; }

exp[len] = ' '; exp[len + 1] = ')'; exp[len + 2] = '\0';

error = false;

operators.push('(');

p = strtok(exp, " ");

while(p && !error) {

if(isdigit(p[0]))

operands.push(atoi(p));

else switch(p[0]) {

case '(' : operators.push('('); break;

case ')' : while (!operators.empty() && !error && operators.top() != '(') {

operation(operators.top()); operators.pop();

}

if (!operators.empty())

operators.pop();

else

error = true;

break;

default : while(!operators.empty() && !error && hasLowerPriority(operators.top(), p[0])) {

operation(operators.top()); operators.pop();

}

operators.push(p[0]);

}

p = strtok(NULL, " ");

}

if(error || !operators.empty() || operands.size() != 1) {

printf("ERROR\n");

while(!operands.empty())

operands.pop();

while(!operators.empty())

operators.pop();

} else {

printf("%d\n", operands.top()); operands.pop();

}

}

return 0;

}


Related Solutions

Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
Using STL stack class, implement in C++ a function that converts an infix expression to postfix...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix expression,
Implement an infix expression to postfix expression convertor in C++. Note: - Support +, -, *,...
Implement an infix expression to postfix expression convertor in C++. Note: - Support +, -, *, /, ( and ) in infix expressions. - Operands will be nonnegative only. - Assume infix expressions are valid and well formatted (one blank space to separate operand/operator) For example, - 3 * 4 + 5 ➔ 3 4 * 5 + - 3 + 4 * 5 ➔ 3 4 5 * + - (3 + 4) * (5 + 6) ➔ 3...
2. Convert the following infix form expression into the postfix form expression by using a stack:...
2. Convert the following infix form expression into the postfix form expression by using a stack: A+(B*(C-D)+E)/F-G*H Show the stack after each push/pop.
Implement in Python using stack operations. Postfix Calculator Post fix calculator • We use a stack...
Implement in Python using stack operations. Postfix Calculator Post fix calculator • We use a stack • When an operand is read, push it on statck • When an operator is read i.e +, *. /, - – Pop two from the top of the stack and apply the operator and push the result on stack if there is one value instead of two display an error message • Keep repeating until an equal sign, = is read; pop from...
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can...
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can be used to evaluate postfix expressions. Please refer to the first 14 pages of this tutorial for postfix expression evaluation: http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdf Requirement: - deal with single digit positive integers only. Operands and operators are fully separated by space. - learn and use STL stack: http://www.cplusplus.com/reference/stack/stack/ - learn and use isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/ - take in a postfix arithmetic expression from cin, and evaluate its value....
Language: Java(Netbeans) Implement a simple calculator.
Language: Java(Netbeans) Implement a simple calculator.
Write a C++ program that converts an infix expression, which includes (, ), +, -, *,...
Write a C++ program that converts an infix expression, which includes (, ), +, -, *, and / operations to postfix notation. The program should allow the user to enter an infix expression using lower case characters, then it will display the result of conversion on the screen. (Note: Use the STL stack class to accomplish the solution.).
In simple Java language algorithm: Implement a static stack class of char. Your class should include...
In simple Java language algorithm: Implement a static stack class of char. Your class should include two constructors. One (no parameters) sets the size of the stack to 10. The other constructor accepts a single parameter specifying the desired size of the stack a push and pop operator an isEmpty and isFull method . Both return Booleans indicating the status of the stack Using the stack class you created in problem 1), write a static method called parse that parses...
An arithmetic expression can be represented in three different formats: infix, prefix, and postfix. In the...
An arithmetic expression can be represented in three different formats: infix, prefix, and postfix. In the infix notation, the operator comes between two operands. In the postfix notation, the operator comes after its two operands. For example, an expression a/b can be transformed to ab/. The following are some examples of the postfix expressions: 2+6*4 Its postfix notation is 2 6 4 * + 2-3+5/4*9-1 Its postfix expression is 2 3 – 5 4 / 9 * + 1 -...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT