This assignment is worth 50 points.
infix postfix
3 + 2 3 2 +
3 - 2 3 2 -
3 / 2 3 2 /
A nice feature of postfix notation is that there is no need for parenthesis. The infix expression 4 + 2 * 5 is normally interpreted as 4 + (2*5). This means that the entire expression must parsed and operator precedence must be applied before the expression can be evaluated. In postfix notation the expression would be 4 2 5 * + which can be evaluated immediately.
Evaluating a postfix expression requires a stack. An expression is processed from left to right. If a number is encountered, it is pushed on the stack. If an operator is encountered, the top two elements are popped from the stack, the operator is applied and the result is pushed back onto the stack. When a correct expression is completely processed, the answer should be the only value remaining on the stack.
Consider processing 4 2 5 * +
Expression Current Element Stack Action
4 2 5 * + 4 Push 4 onto the stack
2 5 * + 2 4 Push 2 onto the stack
5 * + 5 2:4 Push 5 onto the stack
* + * 5:2:4 Pop 5 and 2 from the stack
Compute 2*5
Push 10 onto the stack
+ + 10:4 Pop 10 and 4 from the stack
Compute 4+10
Push 14 onto the stack
empty string none 14 Pop 14 from the stack, this is the answer.
Your assignment is to create a calculator capable of parsing and evaluating expressions given in postfix format.
Expressions will contain only integers, operators from the set {+,-,*,/,%,^} or the word quit. All portions of the expression will be separated by a single space and there may be a space after the last item in an expression. The operations are all binary (two argument) and should be evaluated as integer expressions. All results will fit into an integer.
Under normal operations, your program should prompt with CMD: (with a space at the end). There should be no new line following the prompt. The program should
CMD: 3 5 + Processing 3 5 + 3 5 + = 8
Two error conditions should be handled.
CMD: 3 /
Processing 3 /
Expression error: insufficient operands for /.
Processing of 3 / failed.
CMD: 3 4 + 5 6 - * ^
Processing 3 4 + 5 6 - * ^
Expression error: insufficient operands for ^.
Processing of 3 4 + 5 6 - * ^ failed.
If there any portion of the expression remains to be processed after the error is detected, it should be reported as well.
CMD: 3 4 + 5 6 - * ^ / %
Processing 3 4 + 5 6 - * ^ / %
Expression error: insufficient operands for ^. Unprocessed expression "/ %".
Processing of 3 4 + 5 6 - * ^ / % failed.
In each case, note that the error detail is proceeded by a tab character.
CMD: 2 3
Processing 2 3
Expression error: 1 unused operands.
Processing of 2 3 failed.
A string with a singe number is valid.
CMD: 1 Processing 1 1 = 1
Your program should quit when the quit command is issued.