Model Question Paper (as circulated)Part B · Q11a5 marksCO2Module 1
Question 11a
Evaluate the given expression using stack 4*5/3-(4%2)+(1*5)-2
Transcription notes:
- Printed under Module 2; expression evaluation is Module 1 in the official syllabus. Integer vs real division for 20/3 must be stated.
Topics: Evaluating postfix expressions, Infix to postfix conversion
Watch this exact question run
Loading visualizer…
Other parts: real division
Solution
Assumptions:
- The paper does not say whether / is integer or real division. Because % (remainder) appears, we use integer arithmetic as in C (20 / 3 = 6) and also give the real-division result.
Step 1: convert to postfix. Step 2: evaluate with an operand stack.
| Symbol | Stack | Postfix |
|---|---|---|
| 4 | empty | 4 |
| * | * | 4 |
| 5 | * | 4 5 |
| / | / | 4 5 * |
| 3 | / | 4 5 * 3 |
| - | - | 4 5 * 3 / |
| ( | - ( | 4 5 * 3 / |
| 4 | - ( | 4 5 * 3 / 4 |
| % | - ( % | 4 5 * 3 / 4 |
| 2 | - ( % | 4 5 * 3 / 4 2 |
| ) | - | 4 5 * 3 / 4 2 % |
| + | + | 4 5 * 3 / 4 2 % - |
| ( | + ( | 4 5 * 3 / 4 2 % - |
| 1 | + ( | 4 5 * 3 / 4 2 % - 1 |
| * | + ( * | 4 5 * 3 / 4 2 % - 1 |
| 5 | + ( * | 4 5 * 3 / 4 2 % - 1 5 |
| ) | + | 4 5 * 3 / 4 2 % - 1 5 * |
| - | - | 4 5 * 3 / 4 2 % - 1 5 * + |
| 2 | - | 4 5 * 3 / 4 2 % - 1 5 * + 2 |
| end | empty | 4 5 * 3 / 4 2 % - 1 5 * + 2 - |
| Symbol | Action | Stack |
|---|---|---|
| 4 | push 4 | 4 |
| 5 | push 5 | 4 5 |
| * | 4 * 5 = 20 | 20 |
| 3 | push 3 | 20 3 |
| / | 20 / 3 = 6 | 6 |
| 4 | push 4 | 6 4 |
| 2 | push 2 | 6 4 2 |
| % | 4 % 2 = 0 | 6 0 |
| - | 6 - 0 = 6 | 6 |
| 1 | push 1 | 6 1 |
| 5 | push 5 | 6 1 5 |
| * | 1 * 5 = 5 | 6 5 |
| + | 6 + 5 = 11 | 11 |
| 2 | push 2 | 11 2 |
| - | 11 - 2 = 9 | 9 |
Postfix: 4 5 * 3 / 4 2 % - 1 5 * + 2 - · Result: 9 (integer division)
| Symbol | Action | Stack |
|---|---|---|
| 4 | push 4 | 4 |
| 5 | push 5 | 4 5 |
| * | 4 * 5 = 20 | 20 |
| 3 | push 3 | 20 3 |
| / | 20 / 3 = 6.6667 | 6.6667 |
| 4 | push 4 | 6.6667 4 |
| 2 | push 2 | 6.6667 4 2 |
| % | 4 % 2 = 0 | 6.6667 0 |
| - | 6.6667 - 0 = 6.6667 | 6.6667 |
| 1 | push 1 | 6.6667 1 |
| 5 | push 5 | 6.6667 1 5 |
| * | 1 * 5 = 5 | 6.6667 5 |
| + | 6.6667 + 5 = 11.6667 | 11.6667 |
| 2 | push 2 | 11.6667 2 |
| - | 11.6667 - 2 = 9.6667 | 9.6667 |
Result: 9.6667 (real division)
How to write it in the exam
- Postfix: 4 5 * 3 / 4 2 % − 1 5 * + 2 −
- Integer: 20 / 3 = 6; 4 % 2 = 0; 6 − 0 = 6; 1·5 = 5; 6 + 5 = 11; 11 − 2 = 9 → result 9.
- Real division: 20/3 = 6.6667 → result 9.6667 (29/3).
How this answer was verified
- tests/linear-expression.test.ts asserts 9 (integer) and 29/3 (real)
- postfix_eval.c gives 9