The GATE Grind

GATE 2024 CS (CS1) – Question 33

Compiler Design · Parsing and Syntax Analysis · 1 mark · Numerical answer

Consider the operator precedence and associativity rules for the integer arithmetic operators given in the table: $+$ (Highest, Left), $-$ (High, Right), $*$ (Medium, Right), $/$ (Low, Right). The value of the expression $3+1+5*2/7+2-4-7-6/2$ as per the above rules is __________

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 6

Explanation

Precedence from highest to lowest: $+$ (left-assoc.), $-$ (right-assoc.), $*$ (right-assoc.), $/$ (right-assoc.).

Expression: $3+1+5*2/7+2-4-7-6/2$

1. Evaluate all $+$ first: $(3+1+5)=9$ and $(7+2)=9$, giving $9*2/9-4-7-6/2$.
2. Evaluate $-$ next, right-associative: $4-7-6=4-(7-6)=4-1=3$, then $9-3=6$ (the $-$ binds the neighbouring operands $9,4,7,6$). Expression becomes $9*2/6/2$.
3. Evaluate $*$: $9*2=18$, giving $18/6/2$.
4. Evaluate $/$, right-associative: $6/2=3$, then $18/3=6$.

Value $=\mathbf{6}$.

More Parsing and Syntax Analysis questions

All Parsing and Syntax Analysis questions →