3 + 5 in infix, and 3 5 +
in postfix. Subraction, multiplication and division are
similar, e.g. 3 - 5 versus 3 5 -,
3 * 5 versus 3 5 * and
3 / 5 versus 3 5 /.
Things are more interesting when several operators appear in
one expression. For instance, the postfix expression
3 5 1 - *? What do you do with that?
Well, the first operator is the '-', so immediately to its
left are 1 then 5. Therefore, you subtract 1 from 5 and get
4. After that, you have the '*' applied to 4 and 3, and the
result is 12. If you prefer a picture:
3 5 1 - * 3 5 1 - * 3 4 * = 12So, you evaluate a postfix expression left to right, and whenever you run across an operator, you take it and the two numbers to its left, evalute than simple binary expression, and replace the whole thing with the result. Evalutating even complicated expressions is pretty easy:
3 3 7 8 - 5 + + 2 / 1 + + 3 3 7 8 - 5 + + 2 / 1 + + 3 3 -1 5 + + 2 / 1 + + 3 3 -1 5 + + 2 / 1 + + 3 3 4 + 2 / 1 + + 3 3 4 + 2 / 1 + + 3 7 2 / 1 + + 3 7 2 / 1 + + 3 3.5 1 + + 3 3.5 1 + + 3 4.5 + = 7.5To convince yourself that you understang postfix pretty well Evaluate the following expressions:
pfcalc that's a simple postfix
calculator. You can copy the program with:
cp ~wcbrown/courses/SI221/labs/L06/pfcalc .The program takes in a postfix expression involving +,-,*,/ and numbers (with decimal point if you want it), terminated by an equals sign. A typical run of the program might look like:
valiant[1] [~/]> pfcalc Enter Postfix Expression: 4 2 7 5 - 6 + / * = Expression Evaluates to : 1 valiant[2] [~/]>For Part 1, you're going to write the same kind of program! Now, you might be wondering how exactly to do that. Well, we've just been talking about stacks, so you might guess that they are involved. In fact, with stacks it's easy.
To help you write this program, I'm providing you with
the stack implementation we discussed in class
(Stack.h
or
TradStack.h)
and the following useful function:
pnws. Now, get to work and write a
program that evaluates postfix expressions!
[HINT: remember that cin.get() reads the
next character from the input stream, without skipping whitespace!]
valiant[2] [~/]> pfcalcv2 : 2 3 + = 5 : 2 - = 3 : 4 1 + * = 15 : q valiant[3] [~/]>Notice how left over values on the stack from evaluating one expression simply stay there!
valiant[3] [~/]> pfcalcv3 : 2 3 5 6 - = -1 : p #2 3 -1 : + = 2 : p #2 2 : * = 4 : p #4 : q valiant[4] [~/]>