Question

Consider the following grammar along with translation rules.

S→S1 # T{S.val=S1.val∗T.val}S \to S_1 \,\#\, T \quad \{S.val = S_1.val * T.val\}
S→T{S.val=T.val}S \to T \quad \{S.val = T.val\}
T→T1 % R{T.val=T1.val÷R.val}T \to T_1 \,\%\, R \quad \{T.val = T_1.val \div R.val\}
T→R{T.val=R.val}T \to R \quad \{T.val = R.val\}
R→id{R.val=id.val}R \to \text{id} \quad \{R.val = \text{id}.val\}

Here # and % are operators and id is a token that represents an integer and id.val represents the corresponding integer value. The set of non-terminals is {S,T,R,P}\{S, T, R, P\} and a subscripted non-terminal indicates an instance of the non-terminal.

Using this translation scheme, the computed value of S.val for root of the parse tree for the expression 20 # 10 % 5 # 8 % 2 % 220 \,\#\, 10 \,\%\, 5 \,\#\, 8 \,\%\, 2 \,\%\, 2 is _____________.

Official answer and solution
Official answer
80
From
Official GATE 2022 answer key

Solution

Construct the parse tree according to the grammar rules and compute synthesized attribute values bottom-up.

The grammar is:

S→S1 # T{S.val=S1.val∗T.val}S \to S_1 \,\#\, T \quad \{S.val = S_1.val * T.val\}
S→T{S.val=T.val}S \to T \quad \{S.val = T.val\}
T→T1 % R{T.val=T1.val÷R.val}T \to T_1 \,\%\, R \quad \{T.val = T_1.val \div R.val\}
T→R{T.val=R.val}T \to R \quad \{T.val = R.val\}
R→id{R.val=id.val}R \to \text{id} \quad \{R.val = \text{id}.val\}

The grammar specifies that:

  1. Operator # is left-associative at the SS-level, performing multiplication (∗*).
  2. Operator % is left-associative at the TT-level, performing division (÷\div), with higher precedence than #.

The expression is 20 # 10 % 5 # 8 % 2 % 220 \,\#\, 10 \,\%\, 5 \,\#\, 8 \,\%\, 2 \,\%\, 2.

Evaluating each TT-term:

  • Term 1: T1=20  ⟹  T1.val=20T_1 = 20 \implies T_1.val = 20
  • Term 2: T2=10 % 5  ⟹  10÷5=2T_2 = 10 \,\%\, 5 \implies 10 \div 5 = 2
  • Term 3: T3=8 % 2 % 2T_3 = 8 \,\%\, 2 \,\%\, 2:
    • By left-associativity: (8÷2)÷2=4÷2=2(8 \div 2) \div 2 = 4 \div 2 = 2

Evaluating the SS-level productions:

  • S0→T1  ⟹  S0.val=20S_0 \to T_1 \implies S_0.val = 20
  • S1→S0 # T2  ⟹  S1.val=S0.val∗T2.val=20∗2=40S_1 \to S_0 \,\#\, T_2 \implies S_1.val = S_0.val * T_2.val = 20 * 2 = 40
  • S→S1 # T3  ⟹  S.val=S1.val∗T3.val=40∗2=80S \to S_1 \,\#\, T_3 \implies S.val = S_1.val * T_3.val = 40 * 2 = 80

Thus, the computed value of S.valS.val at the root is 80.

Final answer

80

Common trap

Evaluating % from right to left as 8÷(2÷2)=88 \div (2 \div 2) = 8, violating the left-associative production T→T1 % RT \to T_1 \,\%\, R.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2022 Computer Science and Information Technology (CS)
Question
65 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.