# What is context free grammar? Explain with examples

Data Structure AlgorithmsComputer ScienceComputers

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