CSC211 ยท 2079 ยท 5 marks
Evaluate the postfix expression 574-*8/4+ using stack.
Evaluate the postfix expression 574-*8/4+ using stack. [5]
Evaluating Postfix Expression: 5 7 4 - * 8 / 4 +
Given Data
- Postfix expression:
5 7 4 - * 8 / 4 + - Data structure to use: Stack
Algorithm (Postfix Evaluation)
- Scan the expression left to right.
- If the symbol is an operand, push it onto the stack.
- If the symbol is an operator, pop the top two operands:
op2= first pop (right operand)op1= second pop (left operand)- Compute
op1 <operator> op2and push the result.
- The final remaining stack element is the result.
Step-by-Step Trace
| Step | Symbol | Action | Stack (bottom โ top) |
|---|---|---|---|
| 1 | 5 | Push 5 | 5 |
| 2 | 7 | Push 7 | 5, 7 |
| 3 | 4 | Push 4 | 5, 7, 4 |
| 4 | - | Pop 4, Pop 7 โ $7 - 4 = 3$; Push 3 | 5, 3 |
| 5 | * | Pop 3, Pop 5 โ $5 \times 3 = 15$; Push 15 | 15 |
| 6 | 8 | Push 8 | 15, 8 |
| 7 | / | Pop 8, Pop 15 โ $15 / 8$; Push result | ... |
| 8 | 4 | Push 4 | (result), 4 |
| 9 | + | Pop 4, Pop (result) โ add; Push | final |
Handling the Division at Step 7
The value $15 / 8 = 1.875$.
Case A: Integer division (common in textbook/C-style examples): $$15 / 8 = 1$$ Then:
- Step 8: Push 4 โ stack:
1, 4 - Step 9: $1 + 4 = 5$
Final result = 5
Case B: Real (floating-point) division: $$15 / 8 = 1.875$$ Then:
- Step 8: Push 4 โ stack:
1.875, 4 - Step 9: $1.875 + 4 = 5.875$
Final result = 5.875
Result
Since this is a data structures problem typically evaluated with integer arithmetic, the standard exam answer is:
$$\boxed{5\ 7\ 4\ -\ *\ 8\ /\ 4\ +\ =\ 5}$$
(If real-number division is intended, the result would be $5.875$.)
The trace gives a final value of 5 (using integer division).
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.