## Introduction

Have you ever wondered if you have a much easier language to use than a **regular language** and can also somehow help in the programming language?

Then your search is over! **Context-Free Language** is the answer to your problem. We will learn all about this language in this blog, so let's proceed with our topic without wasting further time.

You can also read about - __Moore Machine__

## Context-Free Grammar(CFG)

You will hear CFG a lot of time in this blog or any other blog related to this topic, so let's first know what CFG is. It stands for Context-Free Grammar.

The grammar is used to create all string patterns from a formal language. It can be defined by using four tuples as shown below:

**G = (V, T, P, S)**

**Also read , **__Arden's theorem__

### Explanation

- G in the above expression stands for grammar. It consists of the set of all the production rules with the help of which we can generate the string of a language.
- T stands for the final set of the terminal symbol. We have to use the lower case alphabet to show them.
- V and T are somewhat opposite as V stands for the set of all non-terminal symbols, and we have to use capital letters to denote it.
- P is the collection of all the production rules used to replace all non-terminals symbols of a string with terminal or other non-terminal symbols.
- S stands for the start symbol, used for deriving string.

### Examples

**Example 1**

Construct the CFG for having any number of b’s over the set **∑= {b}.**

**Solution:**

The regular expression for the above language is

r.e. = b*

Production rules are as given below:

```
S → bS rule 1
S → ε rule 2
```

Now, we will derive the string “bbbbbb.”

```
S
bS
bbS rule 1
bbbS rule 1
bbbbS rule 1
bbbbbS rule 1
bbbbbbS rule 1
bbbbbbε rule 2
bbbbbb
```

The r.e. = b* can generate a set of string {ε, b, bb, bbb,.....}

**Example 2**

Construct a CFG for the expression (0+1)*

**Solution:**

```
Production rule (P):
S → 0S | 1S
S → ε
```

This will result in the set {ε, 0, 1, 01, 10, 00, 11, ....}.

**Example 3**

Construct a CFG for language L = {wcwR | where w € (a, b)*}.

**Solution:**

The production rules can be

```
S → aSa rule 1
S → bSb rule 2
S → c rule 3.
```

Now, we can use it to derive different strings. Let’s take an example of the string “abbcbba”

```
S → aSa
S → abSba from rule 2
S → abbSbba from rule 2
S → abbcbba from rule 3
```

**Example 4**

Construct a CFG for the language L=a^{n}b^{2n}

**Solution:**

This can generate the following output {abb, aabbbb, aaabbbbbb....}.

The production rule is

**S → aSbb | abb. **

If we want to derive the string “aabbbb,” we will proceed like this.

```
S → aSbb
S → aabbbb
```

Also see, __Turing Machine in TOC____.__