As it is defined in question C-5.8 in your textbook, postfix notation is an unambiguous way of writing an arithmetic expression without parentheses. It is defined so that if "(exp1 ) ⊗ (exp2 )" is a normal fully parenthesized expression whose operation is "⊗", then the postfix version of this is "pexp1 pexp2 ⊗", where pexp1 is the postfix version of exp1 and pexp2 is the postfix version of exp2 . The postfix version of a single number or variable is just that number or variable. So, for example, the postfix version of "((5 + 2) * (8 - 3))/4" is "5 2 + 8 3 - * 4 /".
A normal expression may have more than one acceptable fully parenthesized version though. For example 2 + 3 + 4 + 5 can be fully parenthesized as ((2 + 3) + (4 + 5)) or (((2 + 3) + 4 ) + 5). It follows that a normal expression may have more than one equivalent postfix notation. Here are some examples of normal (not necessarily fully parenthesized) expressions and one possible postfix notation for them.
normal expression | postfix notation |
(5+2+3*4)*((2+3)*(5-3)) | 5 2 + 3 4 * + 2 3 + 5 3 - * * |
((8-12) + 4 * 20) / (14 - 12) + 7 | 8 12 - 4 20 * + 14 12 - / 7 + |
12 + 3 - 6 + 8 | 12 3 + 6 - 8 + |
5 * 2 / 4 * 3 | 5 2 * 4 / 3 * |
( 12 + 3 ) - (6 + 8) | 12 3 + 6 8 + - |
postfix expressions can be evaluated non-recursively using stack ADT. The goal of this assignment is to write a program that evaluates a given normal (not necessarily fully parenthesized) expression by transforming it into an equivalent postfix notation, and evaluating that using stacks.
The assignment is broken into 4 steps for you:
string getPostfix(string nexp)
float evaluatePostfix(string pexp)
g++ -c postfixUtility.cpp g++ -o main.o main.cpp postfixUtility.o ./main.o "(4+3* 12)/ ( 12+ 3/ 2+ 46 /4)" 1.6
You can assume there will be only integers, four primitive operators, parentheses, and spaces in the input. Spaces may or may not be present between numbers and operators (or parentheses) in the input but they will appear between separate numbers (for example 5 2 means 5 and then 2 whereas 52 means fifty-two).
While it is OK for you to discuss the high-level idea of how to tackle each of these steps among yourselves, I encourage you to try coming up with the idea yourself. Remember, one of the most important goals of the course is to build your problem-solving skills.