Evaluate Reverse Polish Numeric Expressions

Project #1

Create an interactive program to evaluate Reverse Polish (RPN) numeric expressions. The expression should be a single string containing operands and operators.

Examples

The order (left to right) of operators and operands in Infix and RPN expressions.

Numeric Expressions
InfixRPN (Postfix)
11 + 5 + 211 5 2 + +
11 + 5 - 211 5 2 - +
11 - 5 + 211 5 - 2 +
11 + 5 / 211 5 2 / +
11 / 5 + 211 5 / 2 +
11 * 5 / 211 5 * 2 /
11 / 5 * 211 5 / 2 *
11 + 5 * 211 5 2 * +
11 + 5 / 211 5 2 / +
11 * 5 + 211 5 * 2 +
( 11 + 5 ) * 211 5 + 2 *
11 + ( 5 * 2 )11 5 2 * +

Evaluation Algorithm

loop:

  1. ask the user to enter a RPN expression

    It should be a string containing operators and operands
    separated by commas and/or blanks. (e.g. "1,2 + 4 /")

  2. replace all commas with spaces in the RPN string

  3. split RPN string into separate tokens
    (spaces are token separators)

  4. process the tokens one at a time from left to right

    create a stack for each token: if the token is an operand: push token onto the stack continue if the token is an operator: There should be at least two operands on the stack. If not there is an error. a = pop from the stack b = pop from the stack push (b op a) onto the stack continue display error message break results = pop from the stack display results After obtaining the result, the stack should be empty. If not there is an error.


    Note: This algorithm accepts a more limited (stricter)
    syntax. I.e. operand - operator - operand (infix: a*b)