๐Ÿ“ How Do Computers Understand Grammar?

BNF & Syntax Diagrams

Programming languages have strict grammar rules โ€” just like English. BNF is how we write those rules down, and syntax diagrams (railroad diagrams) show them visually.

CS A-Level Unit 3

๐Ÿค” What is BNF?

BNF (Backus-Naur Form) is a way of writing the grammar rules of a programming language. Just like English has rules ("a sentence needs a subject and a verb"), programming languages have rules about what code looks like.

๐Ÿ• Analogy: Think of ordering pizza. The "grammar" might be:
<order> ::= <size> <topping> "pizza"
<size> ::= "small" | "medium" | "large"
<topping> ::= "pepperoni" | "margherita" | "Hawaiian"
โœ… "large pepperoni pizza" โ€” valid!
โŒ "pepperoni large pizza" โ€” wrong order!
โŒ "huge pepperoni pizza" โ€” "huge" isn't a valid size!
๐Ÿ“‚

Choose a grammar

BNF Rules:
Format: <name> ::= option1 | option2 ยท Terminals in "quotes" ยท Non-terminals in <angle brackets>
๐Ÿ“–

BNF Cheat Sheet

SymbolMeaningExample
::="is defined as"<digit> ::= "0" | "1"
|"or" โ€” choose one option"a" | "b" | "c"
< >Non-terminal โ€” a rule name (gets expanded)<expression>
" "Terminal โ€” an actual character/word (stays as-is)"hello"
<empty>Nothing โ€” the rule can produce an empty string<list> ::= <item> <list> | <empty>
๐Ÿ“ Exam tip: In the exam, you might be asked to write BNF rules for a simple language, or trace through rules to check if a string is valid. Practice by changing the rules above and testing different strings!