What is Context-Free Grammar?



Grammar โˆ’ It is a set of rules which checks whether a string belongs to a particular language a not.

A program consists of various strings of characters. But, every string is not a proper or meaningful string. So, to identify valid strings in a language, some rules should be specified to check whether the string is valid or not. These rules are nothing but make Grammar.

Example โˆ’ In English Language, Grammar checks whether the string of characters is acceptable or not, i.e., checks whether nouns, verbs, adverbs, etc. are in the proper sequence.

Context-Free Grammar

It is a notation used to specify the syntax of the language. Context-free Grammar is used to design parsers.

As Lexical Analyzer generates a string of tokens which are given to parser to construct parse tree. But, before constructing the parse tree, these tokens will be grouped so that the results of grouping will be a valid construct of a language. So, to specify constructs of language, a suitable notation is used, which will be precise & easy to understand. This notation is Context-Free Grammar.

Formally, Context-Free Grammar (G) can be defined as โˆ’

It is a 4-tuple (V,โˆ‘,P,S)

  • V is a set of Non-Terminals or Variables
  • โˆ‘ is a set of terminals.
  • P is a set of Productions or set of rules
  • S is a starting symbol

G is context Free if every Production (P) is of form A โ†’ ฮฑ, where AโˆˆV and ฮฑ โˆˆ(Vโˆช โˆ‘ )*.

Example1 โˆ’ Write down Grammar for language

L={an|nโ‰ฅ1}

Solution

Let G=(V,ฮฃ,P,S)
V = {S}
ฮฃ={a}
P = {
   Sโ†’aS
   Sโ†’a
}

These productions generate language an.

i.e., S โ‡’ a
S โ‡’ a S โ‡’ a a or a2
S โ‡’ a S โ‡’ a a S โ‡’ a a a or a3
.
.
.
S โ‡’ a S โ‡’ a a S โ‡’ a a a S โ‡’ ... โ‡’ an

In Context-Free Grammar, variable or Non-Terminal symbols occur at the left side of โ†’(Arrow). These symbols will be expanded until all terminal symbols will be generated.

The terminal symbols are tokens used in a language.

Example2 โˆ’ Find out language generated by Grammar.

G=({S},{a,b}{S โ†’ a S b,S โ†’ a,b},S)

Solution

S โ‡’ a $\underline{S}$ b

โ‡’ a $\underline{aSb}$ b

โ‡’ a a a $\underline{S}$ b b b

โ‡’ a a a a S b b b b

โ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆ

โ‡’ anโˆ’1$\underline{S}$ bnโˆ’1

โ‡’ anโˆ’1 $\underline{a\:b}$ bnโˆ’1

โ‡’ an bn

โˆด Language L= {an bn| ?โ‰ฅ2}

Example3 โˆ’ Write down CFG G generating all integers.

Solution

G=(V,โˆ‘,P,S)

V = {S, <sign>, <digit>, <integer>}

ฮฃ = {0, 1, 2, 3,โ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆ..9, +, - }

$ P= \begin{Bmatrix} \:\:\:\:S โ†’ <sign> <integer>\ \:\:\:\:\:\:\:\:<sign>โ†’ +|โˆ’\ <integer> โ†’ <digit> <integer>|<digit>\ \:\:\:\: <digit> โ†’ 0 | 1 | 2 | 3โ€ฆโ€ฆโ€ฆโ€ฆ|9 \end{Bmatrix} $

For example, the derivation for โ€“ 12 is given by โˆ’

S โ‡’ <sign> <integer>
? โˆ’<integer>
? โˆ’<digit> <integer>
? โˆ’1<integer>
? โˆ’1<digit>?โˆ’12.
Updated on: 2021-10-26T08:20:44+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements