Dr.Mary Jacob
Department of Computer Science
Kristu Jayanti College(Autonomous),Bengaluru
Evaluation of Postfix Expression
A postfix expression (also called Reverse Polish Notation) is a
mathematical notation in which operators follow their operands.
Example:
Infix: A + B
Postfix: A B +
What is a Postfix Expression?
Why Postfix?
No need for parentheses to define operator precedence.
Easy to evaluate using a stack-based approach.
Algorithm to Evaluate a Postfix Expression
Initialize an empty stack.
Scan the postfix expression from left to right.
For each token in the expression:
1.If the token is an operand, push it onto the stack.
2.If the token is an operator (+, −, ×, ÷):
Ø Pop two operands from the stack (second popped =
operand1, first popped = operand2).
Ø Apply the operator: result = operand1 operator operand2
Ø Push the result back onto the stack.
After the expression is fully scanned, the value left in the stack
is the final result.
Example 1
Example 2
Expression: 5 6 2 + * 12 4 / -
Stack: [5]
Stack: [5, 6]
Stack: [5, 6, 2]
Operator +: Pop 2 and 6 → 6 + 2 = 8 → Stack: [5, 8]
Operator *: Pop 8 and 5 → 5 * 8 = 40 → Stack: [40]
Stack: [40, 12]
Stack: [40, 12, 4]
Operator /: Pop 4 and 12 → 12 / 4 = 3 → Stack: [40, 3]
Operator -: Pop 3 and 40 → 40 - 3 = 37 → Stack: [37]
✅ Final Answer: 37
Thank You

Evaluation of Postfix Expression-Concept and Example

  • 1.
    Dr.Mary Jacob Department ofComputer Science Kristu Jayanti College(Autonomous),Bengaluru Evaluation of Postfix Expression
  • 2.
    A postfix expression(also called Reverse Polish Notation) is a mathematical notation in which operators follow their operands. Example: Infix: A + B Postfix: A B + What is a Postfix Expression?
  • 3.
    Why Postfix? No needfor parentheses to define operator precedence. Easy to evaluate using a stack-based approach.
  • 4.
    Algorithm to Evaluatea Postfix Expression Initialize an empty stack. Scan the postfix expression from left to right. For each token in the expression: 1.If the token is an operand, push it onto the stack. 2.If the token is an operator (+, −, ×, ÷): Ø Pop two operands from the stack (second popped = operand1, first popped = operand2). Ø Apply the operator: result = operand1 operator operand2 Ø Push the result back onto the stack. After the expression is fully scanned, the value left in the stack is the final result.
  • 5.
  • 6.
    Example 2 Expression: 56 2 + * 12 4 / - Stack: [5] Stack: [5, 6] Stack: [5, 6, 2] Operator +: Pop 2 and 6 → 6 + 2 = 8 → Stack: [5, 8] Operator *: Pop 8 and 5 → 5 * 8 = 40 → Stack: [40] Stack: [40, 12] Stack: [40, 12, 4] Operator /: Pop 4 and 12 → 12 / 4 = 3 → Stack: [40, 3] Operator -: Pop 3 and 40 → 40 - 3 = 37 → Stack: [37] ✅ Final Answer: 37
  • 7.