This practical is based on the related lecture: Lecture 3: Context-Free Languages
Exercise 1
For each of the languages below, provide a context-free grammar to generate it:
- (a) $\{\mathtt{b}^{2n}\mathtt{a}^{n}\;|\;n> 0\}$
- (b) A simple programming language consisting of any non-empty sequence of commands separated by "
;". There are only two kinds of commands, namely, a (for assignments), and (nested) if-then-else's. The simple programming language also uses the terminal e (for simple Boolean expressions) and these can be combined with the and and or connectives.
- (c) The set of all strings of
0's and 1's with exactly twice as many 0's as 1's. For instance, your grammar should represent strings such as 010, 001, 100001, and so on.
- (d) $L(((\mathtt{01})^\cup(\mathtt{11}^))\mathtt{000})$
<aside>
💡
Hints
- Refer to our slides on "Designing CFGs".
- Write down strings of length 0, 1, 2, and up to 5 which are elements of the language.
- Repetition of terminal symbols is achieved via a rule in which its left-hand side variable also (recursively) appears on the right-hand side.
</aside>
Exercise 2
For each grammar below, describe its language in the most precise way (that is, answers such as "strings of 0's" are not correct):
- (a) $S\rightarrow \mathtt{a}S\;|\;\mathtt{b}S\;|\;\mathtt{aaa}$
- (b) $S\rightarrow \mathtt{aa}S\;|\;\mathtt{a}S\mathtt{a}\;|\;S\mathtt{aa}\;|\;S\mathtt{b}S\;|\;\epsilon$
- (c) $S\rightarrow\mathtt{0}S\mathtt{0}\;|\;\mathtt{1}S\mathtt{1}\;|\;\epsilon$
<aside>
💡
Hints
- List those strings of length 0, 1, and up to 5 which the grammar generates.
- Try to detect/describe their pattern.
</aside>
Exercise 3
Create grammars that generate exactly the same language as each of the DFAs below:

DFA (a)

DFA (b)