Evaluation of Postfix Expressions
Evaluation of Postfix Expressions
Example:
Let's evaluate the postfix expression:
562-32^*4/+
Step-by-Step Evaluation:
Step Symbol Stack Action
[5, 4, 3,
6 2 Push 2 onto the stack.
2]
Example 2:
Postfix Expression:
4572+*-3/
Step-by-Step Evaluation:
1. Input: Postfix Expression = 4 5 7 2 + * - 3 /
2. Initialize: Stack S = []
3. Process each symbol:
o 4 is an operand → Push onto stack → S = [4]
o 5 is an operand → Push onto stack → S = [4, 5]
o 7 is an operand → Push onto stack → S = [4, 5, 7]
o 2 is an operand → Push onto stack → S = [4, 5, 7, 2]
o + is an operator → Pop 2 and 7, compute 7 + 2 = 9, push result →
S = [4, 5, 9]
o * is an operator → Pop 9 and 5, compute 5 * 9 = 45, push result
→ S = [4, 45]
o - is an operator → Pop 45 and 4, compute 4 - 45 = -41, push result
→ S = [-41]
o 3 is an operand → Push onto stack → S = [-41, 3]
o / is an operator → Pop 3 and -41, compute -41 / 3 ≈ -13.67, push
result → S = [-13.67]
4. Final Stack: S = [-13.67]
o The final result of the postfix expression is approximately -13.67.
Example 3:
Postfix Expression:
10 2 8 * + 3 -
Step-by-Step Evaluation:
1. Input: Postfix Expression = 10 2 8 * + 3 -
2. Initialize: Stack S = []
3. Process each symbol:
o 10 is an operand → Push onto stack → S = [10]
o 2 is an operand → Push onto stack → S = [10, 2]
o 8 is an operand → Push onto stack → S = [10, 2, 8]
o * is an operator → Pop 8 and 2, compute 2 * 8 = 16, push result
→ S = [10, 16]
o + is an operator → Pop 16 and 10, compute 10 + 16 = 26, push
result → S = [26]
o 3 is an operand → Push onto stack → S = [26, 3]
o - is an operator → Pop 3 and 26, compute 26 - 3 = 23, push result
→ S = [23]
4. Final Stack: S = [23]
o The final result of the postfix expression is 23.
Example 4:
Postfix Expression:
234*+56*-
Step-by-Step Evaluation:
1. Input: Postfix Expression = 2 3 4 * + 5 6 * -
2. Initialize: Stack S = []
3. Process each symbol:
o 2 is an operand → Push onto stack → S = [2]
o 3 is an operand → Push onto stack → S = [2, 3]
o 4 is an operand → Push onto stack → S = [2, 3, 4]
o * is an operator → Pop 4 and 3, compute 3 * 4 = 12, push result
→ S = [2, 12]
o + is an operator → Pop 12 and 2, compute 2 + 12 = 14, push result
→ S = [14]
o 5 is an operand → Push onto stack → S = [14, 5]
o 6 is an operand → Push onto stack → S = [14, 5, 6]
o * is an operator → Pop 6 and 5, compute 5 * 6 = 30, push result
→ S = [14, 30]
o - is an operator → Pop 30 and 14, compute 14 - 30 = -16, push
result → S = [-16]
4. Final Stack: S = [-16]
o The final result of the postfix expression is -16.