Past exam question: 2076 Baisakh (Back), Q2
Open in the Padhaiko appQuestion
Define stack. Evaluate the postfix expression A*BC-DE*F/+G* with status of stack where A=2, B=3, C=10, D=5, E=2, F=4 and G=6.
Solution
Definition of Stack: A stack is a linear Abstract Data Type (ADT) following the Last-In, First-Out (LIFO) rule, where all insertions (push) and deletions (pop) occur at a single end called top.
Postfix Evaluation Trace for AB*C-DE*F/+G* (A=2, B=3, C=10, D=5, E=2, F=4, G=6): Substituting values: 2 3 * 10 - 5 2 * 4 / + 6 *
| Symbol | Value / Operation | Stack (Bottom Top) |
|---|---|---|
A | Push 2 | [2] |
B | Push 3 | [2, 3] |
* | Pop 3, 2 | [6] |
C | Push 10 | [6, 10] |
- | Pop 10, 6 | [-4] |
D | Push 5 | [-4, 5] |
E | Push 2 | [-4, 5, 2] |
* | Pop 2, 5 | [-4, 10] |
F | Push 4 | [-4, 10, 4] |
/ | Pop 4, 10 | [-4, 2.5] |
+ | Pop 2.5, -4 | [-1.5] |
G | Push 6 | [-1.5, 6] |
* | Pop 6, -1.5 | [-9] |
(Note: Under C integer division , the result would be .)
Answer:
Under the corrected postfix expression AB*C-DE*F/+G*, the final evaluated value is (or under integer division). Note that the literal printed expression A*BC-DE*F/+G* underflows at the first *.