Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

TOPIC:- Context free Grammar

YADWINDER KAUR
ROLL NO :-21071273
MCA 2 YEARS(3 SEM)
Context free Grammar
a quintuple (V, T, P, S) where
V is a finite set of nonterminals, containing S,
T is a finite set of terminals,
P is a set of production rules in the form of β where  and β are strings over V UT , and
S is the start symbol.
Example
G= ({S, A, B, C}, {a, b, c}, P, S)
P= {SSABC,BA  AB, CB  BC,CA  AC,SA  a, aA  aa, aB  ab,
bB  bb, bC  bc, cC  cc}
Derivation
Derivation is a sequence of production rules. It is used to get the input string through these production rules. During parsing we have to
take two decisions. These are as follows:
We have to decide the non-terminal which is to be replaced.
We have to decide the production rule by which the non-terminal will be replaced.
We have two options to decide which non-terminal to be replaced with production rule.

Leftmost and Rightmost Derivation


LEFTMOST DERIVATION:- Each step of the derivation is a replacement of the leftmost nonterminals in a sentential form.

EXAMPLE:- X → X+X → a+X → a + X*X → a+a*X → a+a*a

RIGHTMOST DERIVATION:- A rightmost derivation is obtained by applying production to the rightmost variable in each step.

EXAMPLE:- X → X*X → X*a → X+X*a → X+a*a → a+a*a


Parse Tree
A labeled tree in which
the interior nodes are labeled by nonterminals
leaf nodes are labeled by terminals
the children of an interior node represent a replacement of the associated nonterminal in a derivation
corresponding to a derivation
E
id
+
F

id E
*

id
Parse Trees and Derivations
E1
EE+E (1)
E2 E 3

+

id + E (2)
E4 E5 
id + E * E (3)
id *

id + id * E (4)
id id 
id + id * id (5)
Preorder numbering EE+E (1)

E+E*E (2)
E 1

E + E * id (3)
E5 + E2 
E + id * id (4)

id + id * id (5)
id E4 * E3
id id

Reverse of postorder numbering


Leftmost, Rightmost Derivations
A left-most derivation of a sentential form is one in
which rules transforming the left-most non terminal are always
applied.

A Right-most derivation of a sentential form is one in


which rules transforming the right-most non terminal are always
applied.
Ambiguous Grammar
f a context free grammar G has more than one derivation tree for some string w ∈ L(G), it
is called an ambiguous grammar. There exist multiple right-most or left-most derivations
for some string generated from that grammar.

Problem
Check whether the grammar G with production rules −
X → X+X | X*X |X| a
is ambiguous or not.

Solution
Let’s find out the derivation tree for the string "a+a*a". It has two leftmost derivations.
Example:-
Derivation 1 − X → X+X → a +X → a+ X*X → a+a*X → a+a*a
Parse tree 1 −

You might also like