Skip to content
Official PYQ · 2017

GATE CS 2017 Set 1 Q43 — Parsing (LL, LR)

Explain with AI

Consider the following grammar:

  • stmt →\rightarrow if expr then expr else expr; stmt | OˋÒ
  • expr →\rightarrow term relop term | term
  • term →\rightarrow id | number
  • id →\rightarrow a | b | c
  • number →[0−9]\rightarrow [0-9] 

where relop is a relational operator ((e.g., <,>,…),< , >,\ldots), OˋÒ refers to the empty statement, and if, then, else are terminals. 
Consider a program PP following the above grammar containing ten if terminals. The number of control flow paths in PP is________ . For example. the program 
if e1e_1 then e2e_2 else e3e_3 
has 22 control flow paths. e1→e2e_1 \rightarrow e_2 and e1→e3e_1 \rightarrow e_3. 

View worked solution

Answer: 1024

To find the number of control flow paths in a program PP containing ten if terminals, we analyze the structure of the program generated by the given grammar.

1. Program Structure

The grammar rule for statements is:

stmt→if expr then expr else expr;stmt∣ϵ\text{stmt} \rightarrow \textbf{if } \text{expr} \textbf{ then } \text{expr} \textbf{ else } \text{expr}; \text{stmt} \mid \epsilon

Here, OˋÒ represents the empty statement ϵ\epsilon. Since the recursion occurs at the end of the rule, a program PP containing ten if terminals consists of a sequence of 1010 independent if-then-else statements executed one after another:

stmt1;stmt2;… ;stmt10\text{stmt}_1; \text{stmt}_2; \dots; \text{stmt}_{10}

2. Paths per Statement

As given in the example, a single if-then-else statement:

if e1 then e2 else e3\textbf{if } e_1 \textbf{ then } e_2 \textbf{ else } e_3

has exactly 22 control flow paths:

  • Path 1: e1→e2e_1 \rightarrow e_2 (when the condition is true)
  • Path 2: e1→e3e_1 \rightarrow e_3 (when the condition is false)

3. Total Control Flow Paths

Since the 1010 statements are executed sequentially, the choices made in each statement are independent of the others. By the product rule of combinatorics, the total number of control flow paths through the program is:

Total Paths=2×2×⋯×2 (10 times)=210=1024\text{Total Paths} = 2 \times 2 \times \dots \times 2 \text{ (10 times)} = 2^{10} = 1024

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

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