Evaluation of Postfix Expression-Concept and Example
MaryJacob24
12 views
7 slides
May 03, 2025
Slide 1 of 7
1
2
3
4
5
6
7
About This Presentation
Evaluation of Postfix Expression-Concept and Example
Size: 134.76 KB
Language: en
Added: May 03, 2025
Slides: 7 pages
Slide Content
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