Search⌘ K

Context-free Grammars and Derivations

Learn to define context-free grammars (CFGs) and perform derivations to generate languages in computation. This lesson covers CFG components, example grammars for balanced strings, palindromes, and languages with symbol count constraints. Discover how CFGs model complex language structures and support automata theory. Understand closures under operations like concatenation and how CFGs represent important computational languages.

We'll cover the following...

Let’s formally define context-free grammar (CFG).

Context-free grammar

A context-free grammar is a formal grammar consisting of the following:

  • A set of variables (i.e., a nonterminal alphabet), VV, one of which is a start variable.
  • An alphabet, Σ\Sigma, of terminal symbols.
  • A set of production rules of the form vsv\rightarrow s, where vVv\in V and s(VΣ)s\in (V\cup\Sigma)^*, a string of terminals and/or variables.

Let’s look at some illustrations of CFGs for some of the languages.

Examples of CFGs

The following CFG generates the language {anbn    n>0}\{a^nb^n\;|\;n>0\}:

As a reminder, using the alternation symbol “\mathbf{|}” allows us to combine all the productions for a given variable on a single line. This grammar can also be expressed as:

The smallest string in the language is abab, which occurs by choosing the second rule above. To generate the language {anbn    n0}\{a^nb^n \;|\; n\geq 0\}, we would replace abab with the empty string.


To generate the language {anb2n    n0}\{a^nb^{2n} \;|\; n\geq 0\}, we generate two bb’s for every aa:

We derive the string aabbbbaabbbb like this:


To construct a CFG for the language {aibj    ij}\{a^ib^j\;|\;i\neq j\} ...