Cfg Solved Examples !!top!! ★ High-Quality & Recommended
| Language pattern | CFG trick | |----------------|------------| | ( a^n b^n ) | ( S \to aSb \mid \varepsilon ) | | Matching parentheses | ( S \to SS \mid (S) \mid \varepsilon ) | | ( a^n b^m, n\le m ) | ( S \to aSb \mid bS \mid \varepsilon ) | | Palindromes | ( S \to aSa \mid bSb \mid a \mid b \mid \varepsilon ) | | ( a^i b^j c^i+j ) | Separate S for a’s + c’s, T for b’s + c’s | | Equal #a and #b (any order) | ( S \to aSbS \mid bSaS \mid \varepsilon ) | | Expression grammar | Left-recursive for left-assoc operators |
Here are some solved examples of context-free grammars:
Zero or more repetitions of the same pattern. cfg solved examples
( L = ( a^n b^n )^* )
( S \Rightarrow A B \Rightarrow (aAb) B \Rightarrow (a(ε)b) B \Rightarrow ab B \Rightarrow ab (aB) \Rightarrow ab a (a) \Rightarrow abaa ) (Wait, that gave 3a,1b. Let's fix.) Better grammar: ( S \to a S \mid a S b \mid \varepsilon ) – No, that generates arbitrary. Corrected approach: ( S \to a S b \mid a S \mid a ) Corrected approach: ( S \to a S b
E → E + T → T + T → F + T → 2 + T → 2 + T * F → 2 + 3 * F → 2 + 3 * 4
Rule 1 handles nesting, while Rule 2 handles concatenation (e.g., ()() ). while Rule 2 handles concatenation (e.g.
: ( a^n b^n \mid n \ge 0 )