IAE Academy

ISRO CS 2023 Q.8: solution and answer

ISRO 2023 · CSQ.8 · 1 mark · MCQ

Consider the context-free grammar G below for arithmetic expressions:
E → E + E | E × E | id
Which of the following statements is TRUE:

  1. (A)

    The string “id + id × id” has no parse tree according to G

  2. (B)

    The string “id + id × id” has only one parse tree according to G

  3. (C)

    The string “id + id × id” has exactly two parse trees according to G

  4. (D)

    The string “id + id × id” has more than two parse trees according to G

See the question in the paper

Answer and solution

ANSWER

Option (c): the string id + id × id has exactly two parse trees, so G is ambiguous.

Official answer: CSource: ISRO's revised and final answer key of 16 February 2024

  1. The grammar is . It gives no precedence or associativity, so a string with several operators can be grouped in more than one way.

  2. The string id + id × id has two operators. The root of a parse tree uses either or , and the root's operator is the one applied last. The root cannot use , because the string has more than one token.

  3. Root : the string splits at the +. The left must derive id, which is possible only by . The right must derive id × id, which is possible only by with each side . This gives exactly one tree, with grouping .

  4. Root : the string splits at the ×. The left must derive id + id, which is possible only by with each side . The right derives id. This gives exactly one tree, with grouping .

  5. Each operator occurs once in the string, so each root choice splits the string at a single, fixed place, and each part has a unique tree. The total is parse trees.

  6. So trees exist (option (a) is false), more than one exists (option (b) is false), and there are not more than two (option (d) is false). The statement that the string has exactly two parse trees is true: option (c).

KEY IDEA

Count parse trees by choosing the root production, which fixes which operator is applied last. Then count the trees of the two sub-strings. With no precedence in the grammar, each operator can be the root.

WATCH OUT FOR

Assuming that × binds tighter than +, as in school arithmetic, and so counting only the tree id + (id × id). The grammar encodes no precedence, so (id + id) × id is also a valid parse tree.

From the ISRO CS 2023 paper. Every question of this paper · The full paper (PDF, ISRO) · All 6 ISRO CFG & PDA questions, with notes

More ISRO CFG & PDA questions