Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
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.

Integer division (as in C)checked by code
SymbolStackPostfix
4empty4
**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
endempty4 5 * 3 / 4 2 % - 1 5 * + 2 -
SymbolActionStack
4push 44
5push 54 5
*4 * 5 = 2020
3push 320 3
/20 / 3 = 66
4push 46 4
2push 26 4 2
%4 % 2 = 06 0
-6 - 0 = 66
1push 16 1
5push 56 1 5
*1 * 5 = 56 5
+6 + 5 = 1111
2push 211 2
-11 - 2 = 99

Postfix: 4 5 * 3 / 4 2 % - 1 5 * + 2 - · Result: 9 (integer division)

Same postfix with real divisionchecked by code
SymbolActionStack
4push 44
5push 54 5
*4 * 5 = 2020
3push 320 3
/20 / 3 = 6.66676.6667
4push 46.6667 4
2push 26.6667 4 2
%4 % 2 = 06.6667 0
-6.6667 - 0 = 6.66676.6667
1push 16.6667 1
5push 56.6667 1 5
*1 * 5 = 56.6667 5
+6.6667 + 5 = 11.666711.6667
2push 211.6667 2
-11.6667 - 2 = 9.66679.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