4.5Expression Notations and Infix to Postfix Conversion
Covers IGNOU MCS-208 §4.5
The study material lists expression conversion and evaluation as the main applications of stacks. To evaluate an expression like A + B * C, a program must know that * is done before +. Converting the expression to postfix form removes the need for precedence rules and brackets, and a stack does the conversion.
Three notations
Notation
Operator position
Example for (A+B)×C
Infix
Between the operands
(A + B) * C
Prefix (Polish)
Before the operands
* + A B C
Postfix (reverse Polish)
After the operands
A B + C *
Prefix and postfix need no brackets: the position of each operator already says which operands it applies to. They were introduced by the Polish logician Jan Łukasiewicz, hence “Polish notation”.
Precedence and associativity
Operator
Precedence
Associativity
^ (power)
3 (highest)
Right to left: A^B^C = A^(B^C)
*/
2
Left to right: A/B*C = (A/B)*C
+-
1
Left to right: A-B+C = (A-B)+C
The conversion algorithm
Scan the infix expression from left to right:
Operand: append it to the output.
(: push it.
): pop operators to the output until a ( is on top; pop and discard the (.
Operator op: while the top of the stack is an operator that has higher precedence than op, or equal precedence with op left-associative, pop it to the output. Then push op.
End of input: pop all remaining operators to the output.
Each symbol is pushed and popped at most once, so the conversion is O(n) for an expression of n symbols.
Key takeaways
Infix: operator between operands; prefix: before; postfix: after. Prefix and postfix need no brackets.
Precedence: ^ > */ > +-; ^ is right-associative, the others left-associative.
Conversion: operands to output, operators wait on a stack, ) pops back to (.
Each symbol is pushed and popped at most once: O(n).
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Convert A * (B + C) - D / E to postfix using a stack, showing the stack after each symbol.
Show worked answer
(symbol: stack | output) A: empty | A; *: * | A; (: * ( | A; B: * ( | A B; +: * ( + | A B; C: * ( + | A B C; ): * | A B C +; -: - | A B C + * (the * has higher precedence and is popped); D: - | A B C + * D; /: - / | A B C + * D (/ is higher than -, so it is pushed); E: - / | A B C + * D E; end: empty | A B C + * D E / -. Postfix: A B C + * D E / -.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-208/stacks/expression-notations-and-infix-to-postfix-conversion/ to read this page.