Skip to content
Official PYQ · 2003

GATE CS 2003 Q58 — Parsing (LL, LR)

Explain with AI

Consider the translation scheme shown below.

  • S→T  RS \rightarrow T\;R
  • R→+T{print(‘+’);}R∣εR \rightarrow + T \{\text{print}(‘+’);\} R\mid \varepsilon
  • T→T \rightarrow num {print\{\text{print}(num.val);};\}

Here num is a token that represents an integer and num.val represents the corresponding integer value. For an input string ‘9+5+29 + 5 + 2’, this translation scheme will print

Choose one option
View worked solution

Answer: B

To find the output printed by the translation scheme for the input string 9 + 5 + 2, we construct the parse tree and execute the semantic actions during a depth-first (left-to-right) traversal.

1. Parse Tree Construction

The input string is 9 + 5 + 2. The parse tree based on the given grammar is shown below:

       S
      / \
     T   R
     |   / | \
     9  +  T  {print('+')}  R
           |               / | \
           5              +  T  {print('+')}  R
                             |                |
                             2                ε

2. Traversal and Action Execution

We perform a left-to-right depth-first traversal of the parse tree, executing the semantic actions (enclosed in curly braces { }) as they are encountered:

  1. Traverse the leftmost child of SS, which is T→num{print(num.val);}T \rightarrow \mathbf{num}\{\text{print}(\mathbf{num}.\text{val});\} with num.val=9\mathbf{num}.\text{val} = 9.
    Action: print(9)
    Output so far: 9
  2. Move to RR. Match the terminal symbol +.
  3. Traverse T→num{print(num.val);}T \rightarrow \mathbf{num}\{\text{print}(\mathbf{num}.\text{val});\} with num.val=5\mathbf{num}.\text{val} = 5.
    Action: print(5)
    Output so far: 9 5
  4. Execute the action associated with R→+T{print(′+′);}RR \rightarrow + T \{\text{print}('+');\} R.
    Action: print('+')
    Output so far: 9 5 +
  5. Traverse the nested RR. Match the terminal symbol +.
  6. Traverse T→num{print(num.val);}T \rightarrow \mathbf{num}\{\text{print}(\mathbf{num}.\text{val});\} with num.val=2\mathbf{num}.\text{val} = 2.
    Action: print(2)
    Output so far: 9 5 + 2
  7. Execute the action associated with the nested RR.
    Action: print('+')
    Output so far: 9 5 + 2 +
  8. Traverse the innermost R→εR \rightarrow \varepsilon, which performs no action.

The final printed output is 9 5 + 2 +.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Parsing (LL, LR) questions