Context Free Grammar (CFG)

In this article, we have explained Context Free Grammar (CFG) in depth along with examples and real life applications of Context Free Grammar (CFG). This is one of the most important concept in Theory of Computation.

Table of contents:

  1. What is Context Free Grammar (CFG)?
  2. Example of Context Free Grammar
  3. Properties of Context Free Grammar
  4. Application of Context Free Grammar (CFG)

Let us get started.

What is Context Free Grammar (CFG)?

Context Free Grammar is defined as a 4 tuple G = (V, Σ, R, S) where:

  1. V is a finite set of elements known as variables.
  2. Σ is a finite set of elements known as terminals
  3. V ∩ Σ = Null (empty set)
  4. S is an element of V and is known as start variable.
  5. R is a fine set of elements known as rule. Each rule is like A -> w where A belongs to V and w belongs to union of (V and Σ)*. The * denotes repetation of elements.

An example of Context Free Grammer is:

G = (V, Σ, R, S) where:

The above Context Free Grammer is for Balanced Parentheses expressions consisting of round bracket only ().

Definitions of Context Free Grammers:

uAv => uwv. 

Example of Context Free Grammar

This is the example of a Context free grammar (CFG) for Balanced Parentheses:

Let us assume we want to arrive at the balanced expression (())()() using our context free grammer G.

To get the complete idea of this Context Free Grammer, go through this article.

Properties of Context Free Grammar

Following are the properties of Context Free Grammer:

Therefore, all Regular Languages = Context Free Languages.
Some / not all Non-regular Languages = Context Free Languages.

If a Language L is not a Context Free Language, then the language L is a Non-regular Language.

Applications of Context Free Grammar (CFG)

Following is the Context Free Grammer for HTML (with limited tags):

Following is the Context Free Grammer for an Imperative Programming Language Brainfuck:

There are syntax features that cannot be represented with a Context Free Grammer such as:

Therefore, Programming Languages / Real life programs are not represented purely by Context Free Grammer.

G is a Context Free Grammer

Start variable = S

Example of sentences generated using it are:

It also generates some invalid sentences:

With this article at OpenGenus, you must have the complete idea of Context Free Grammer which is one of the most important ideas in Theory of Computation.

OpenGenus IQ © 2024 All rights reserved ™
Contact - Email: team@opengenus.org
Primary Address: JR Shinjuku Miraina Tower, Tokyo, Shinjuku 160-0022, JP
Office #2: Commercial Complex D4, Delhi, Delhi 110017, IN