2079 9

CSC211 ยท 2079 ยท 5 marks

Evaluate the postfix expression 574-*8/4+ using stack.

Evaluate the postfix expression 574-*8/4+ using stack. [5]

Data Structures and AlgorithmsChapter 2: StackConversion from infix to postfix/prefix expression, EvaluatiNumerical: postfix expression evaluation

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)

  1. Scan the expression left to right.
  2. If the symbol is an operand, push it onto the stack.
  3. If the symbol is an operator, pop the top two operands:
    • op2 = first pop (right operand)
    • op1 = second pop (left operand)
    • Compute op1 <operator> op2 and push the result.
  4. The final remaining stack element is the result.

Step-by-Step Trace

StepSymbolActionStack (bottom โ†’ top)
15Push 55
27Push 75, 7
34Push 45, 7, 4
4-Pop 4, Pop 7 โ†’ $7 - 4 = 3$; Push 35, 3
5*Pop 3, Pop 5 โ†’ $5 \times 3 = 15$; Push 1515
68Push 815, 8
7/Pop 8, Pop 15 โ†’ $15 / 8$; Push result...
84Push 4(result), 4
9+Pop 4, Pop (result) โ†’ add; Pushfinal

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.