What is context free grammar? Explain with examples


A context free grammar (CFG) is a forma grammar which is used to generate all the possible patterns of strings in a given formal language.

It is defined as four tuples −

G=(V,T,P,S)

  • G is a grammar, which consists of a set of production rules. It is used to generate the strings of a language.
  • T is the final set of terminal symbols. It is denoted by lower case letters.
  • V is the final set of non-terminal symbols. It is denoted by capital letters
  • P is a set of production rules, which is used for replacing non-terminal symbols (on the left side of production) in a string with other terminals (on the right side of production).
  • S is the start symbol used to derive the string

Example

Construct CFG for the language having any number of a's over the set ∑={a}

Solution

Regular Expression= a*

Production rule for the Regular Expression is as follows −

S->aS rule 1

S-> ε rule 2

Now if we want to derive a string "aaaaaa" we can start with start symbol

Start with start symbol:

srule
aS1
aaS1
aaaS1
aaaaS1
aaaaaS1
aaaaaaS1
aaaaaa2

The regular expression=a* can generate a set of strings { ε,a,aa,aaa,...}

We can have a null string because S is a start symbol and rule 2 gives S-> ε

Updated on: 11-Jun-2021

40K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements