# Eliminating Left Recursion from a Grammar

Recursion can be classified into three types.

- Left Recursion
- Right Recursion
- General Recursion

**Left Recursion**

- A production of grammar is Left recursive if the leftmost variable (Non-Terminal) of its RHS is similar to a variable of its LHS.
- Left Recursive Grammar is a grammar having a left recursion.

## Example of Eliminating Left Recursion from a Grammar

How to find the first and follow functions for the given CFG with Left Recursive production rules.?

S → H

H → aF / H d

F → b

C → t

The given grammar is left recursive. So, we first remove the left recursion from the given grammar.

After the elimination of left recursion, we get the following grammar.

S → H

H → a F H’

H’ → d H’ / ∈

F → b

C → t

The first and follow functions are described below;

__First Functions__

- First(S) = First(H) = { a }
- First(H) = { a }
- First(H’) = { d , ∈ }
- First(F) = { b }
- First(C) = { t }

__Follow Functions__

- Follow(S) = { $ }
- Follow(H) = Follow(S) = { $ }
- Follow(H’) = Follow(H) = { $ }
- Follow(F) = { First(A’) – ∈ } ∪ Follow(A) = { d , $ }
- Follow(C) = NA

## Problem with Left Recursion

If a left recursion is present in any grammar then, it can lead to an infinite loop.

## Example 2 of Removing Left Recursion from a CFG

How to find the first and follow functions for the given CFG with Left Recursive production rules.?

P→ P + Q / Q

Q → Q d F / F

F → (P) / id

__Solution-__

The given grammar is left recursive. So, we first remove the left recursion from the given grammar.

After the elimination of left recursion, we get the following grammar.

P → Q P’

P’ → + Q P’ / ∈

Q → F Q’

Q’ → d F Q’ / ∈

F → (P) / id

The first and follow functions are described below;

__First Functions__

- First(P) = First(Q) = First(F) = { ( , id }
- First(P’) = { + , ∈ }
- First(Q) = First(F) = { ( , id }
- First(Q’) = { d , ∈ }
- First(F) = { ( , id }

__Follow Functions__

- Follow(P) = { $ , ) }
- Follow(P’) = Follow(E) = { $ , ) }
- Follow(Q) = { First(P’) – ∈ } ∪ Follow(P) ∪ Follow(P’) = { + , $ , ) }
- Follow(Q’) = Follow(Q) = { + , $ , ) }
- Follow(F) = { First(Q’) – ∈ } ∪ Follow(Q) ∪ Follow(Q’) = { d , + , $ , ) }