What is ContextFree Grammar? (original) (raw)

What is Context-Free Grammar?

Last Updated : 23 Jul, 2025

A grammar consists of one or more variables that represent classes of strings (i.e., languages) . There are rules that say how the strings in each class are constructed. The construction can use :

Context-Free Grammar

A **context-free grammar (CFG) is a formal system used to describe a class of languages known as **context-free languages (CFLs). Purpose of context-free grammar is:

A GFG (or just a grammar) G is a tuple G = (V, T, P, S) where

A grammar is said to be the Context-free grammar if every production is in the form of:

G -> (V∪T)* , where G ∊ V

The above equation states that every production which contains any combination of the 'V' variable or 'T' terminal is said to be a context-free grammar.

**Core Concepts of CFGs

A CFG is defined by:

**CFG vs. Other Models

Model Description
**Finite Automata Accept strings via computation (accept/reject).
**Regular Expressions Match strings by describing their structure.
**CFG Generate strings via recursive replacement.

**Example: Arithmetic Expressions

Suppose we want to describe all legal arithmetic expressions using addition, subtraction, multiplication, and division.

Here is one possible :

**Production Rules:

CFG:
E → int
E → E Op E
E → (E)
Op → +
Op → -
Op → *
Op → /

**Example Derivation:

E
⇒ E Op E
⇒ E Op int
⇒ int Op int
⇒ int / int

**Designing a CFG

When creating CFGs:

  1. **Base case: Define the simplest valid strings.
  2. **Recursive rules: Combine smaller components into larger ones.

Examples:

**1. Palindromes over {a, b}:

S → ε | a | b | aSa | bSb

**2. Balanced Parentheses:

S → ε | (S) | SS

**Languages Defined by CFGs

The language L(G) generated by a CFG G is: L(G)={ _ω_∈Σ*∣__S_⇒∗__ω}

**Regular Languages vs. Context-Free Languages

**Property **Regular Languages **Context-Free Languages
**Power Limited More expressive
**Memory Requirements Finite Unbounded recursion
**Definable Structures Simple patterns (e.g., repetition) Nested structures (e.g., palindromes, balanced parentheses)

Non-CFG Example

Productions such as:

a->bSa, or
a->ba is not a CFG as on the left-hand side there is a terminal which does not follow the CFGs rule.

But we can construct it by :

Lets consider the string "**aba" and and try to derive the given grammar from the productions given. We start with symbol **S, apply production rule S->bSa and then (S->a) to get the string "aba".

b

Parse tree of string "aba"

In the computer science field, context-free grammars are frequently used, especially in the areas of formal language theory, compiler development, and natural language processing. It is also used for explaining the syntax of programming languages and other formal languages.

**Limitations of Context-Free Grammar