in Compiler Design edited by
9,550 views
39 votes
39 votes

Which one of the following grammars is free from left recursion?

  1. $S \rightarrow AB$
    $A \rightarrow Aa \mid b$
    $B \rightarrow c$
  2. $S \rightarrow Ab \mid Bb \mid c$
    $A \rightarrow Bd \mid \epsilon$
    $B \rightarrow e$
  3. $S \rightarrow Aa \mid B$
    $A \rightarrow Bb \mid Sc \mid \epsilon$
    $ B \rightarrow d$
  4. $S \rightarrow Aa \mid Bb \mid c$
    $A \rightarrow Bd \mid \epsilon$
    $B \rightarrow Ae \mid \epsilon$
in Compiler Design edited by
9.6k views

1 comment

A context free grammar is said to be left recursive if it has a non-terminal $A$ such that there is a derivation $A ⇒^+ Aα$  for some sequence of grammar symbols $α$. 
For Example:

The following grammar is left-recursive:
$A → Bb ; A → a$
$B →Cc ; B → b$
$C → Aa ; C → c $
 

0
0

4 Answers

60 votes
60 votes
Best answer

Option (A) has immediate left recursion."$A \rightarrow Aa$"

Option (C) has indirect left recursion "$S\rightarrow Aa \stackrel{A\rightarrow Sc}{\Longrightarrow} Sca$"

Option (D) has indirect left recursion "$A\rightarrow Bd \stackrel{B\rightarrow Ae}{\Longrightarrow} Aed$"

Option (B) is free from left recursion. No direct left recursion. No indirect left recursion.

Correct Option: B

edited by

3 Comments

Ashish Sir, why (b) is not in left recursion since it is of the form A->Ba/b where a,b∊T*. I think the answer should be (a)
0
0
@ashish why not be is direct left recursion????I did not get plz clarify
0
0
Option A cannot be free from left recursion because term A->Aa causes left recursion.
0
0
10 votes
10 votes
make the dependency graph on basis of variable if there is any no cycle then it is free from left recursion

1 comment

please show how would u draw the precedence graph for the same
0
0
0 votes
0 votes
A has left recursion directly in the second production.

 

For other options, remove the epsilon production from them. In the resulting set of productions try to take each Terminal and see if substituting it directly in other places will lead to left recursion.

 

This ends up happening In options C and D, where Terminal A produces left recursion in terminal S, and Terminal B produces left recursion in terminal  A respectively.

 

Thus B is the answer
0 votes
0 votes
Take some sample input, 1 to 2 random language would work, then try making a parse tree either in mind or pen and paper would work. You will get to see that apart from option (B), the rest all are showing left recursion some or the other way. While in option B if we simply substitute single productions into the respective productions, it’s visible that left recursion doesn’t exist. I hope this helps.

1 comment

Indirect left recursion means when we go from one production to another production and then that new productions sends back to the last production from which we came. Here the production is of the form:

X → Y a

Y → X b
0
0
Answer:

Related questions