# How to convert CFG to Greibach Normal Form?

Data Structure AlgorithmsComputer ScienceComputers

A Context Free Grammar (CFG) is said to be in Greibach Normal Form(GNF), if production rules satisfy one of the following criteria −

• Only a start symbol can generate ε. For example, if S is the start symbol then S → ε is in GNF.

• A non-terminal can generate a terminal. For example, if A is Non terminal and a is terminal then, A → a is in GNF.

• A non-terminal can generate a terminal followed by any number of non-terminals. For Example, S → aAS is in GNF.

## Case 1

G1 = {S → aAB | aB, A → aA| a, B → bB | b}

The production rules of G1 satisfy the rules specified for GNF, then the grammar G1 is in GNF.

## Case 2

G2 = {S → aAB | aB, A → aA | ε, B → bB | ε}

The production rule of G2 is not satisfying the rules specified for GNF as

A → ε and B → ε contain ε(only the start symbol can generate ε).

So, the grammar G2 is not in GNF.

## Steps for converting CFG into GNF

• Step 1 − Convert the grammar into CNF. If the given grammar is not in CNF, convert it into CNF.

• Step 2 − If the grammar consists of left recursion, eliminate it. If the context free grammar contains any left recursion, eliminate it.

• Step 3 − In the grammar, convert the given production rule into GNF form. If any production rule in the grammar is not in GNF form, convert it.

Example

Consider the context free grammar

S→SS|(S)|a

Convert this grammar to Greibach Normal Form.

Solution

Given below is an explanation for conversion of CFG to GNF −

Step 1:
Converting to CNF:
S->SS|XSY|a
X->(
Y->)

Step 2:
Remove left recursion from S->SS
S->XSYP/aP
P->SP/ε
X->(
Y->)

Step 3:
Remove null production P->ε
S->XSYP/aP
P->SP/S
X->(
Y->)

Step 4:
Convert to GNF as S->XSYP is not in GNF,
Replace X with (
S->(SYP/aP
P->SP/S
X->(
Y->)

Step 5:
Convert to GNF as P->SP is not in GNF,
Replace S with (SYP/aP
S->(SYP/aP
P->(SYPP/aPP/(SYP/aP
X->(
Y->)
Published on 15-Jun-2021 11:25:06