Back to the 2026 paper

Module 1: Introduction, Lexical Analysis

20267m

Explain the different phases of compilation with a suitable example. Show the input and output produced at each phase.

Worked SolutionAI Assisted

Phases of a compiler

A compiler translates a source program into target code in a sequence of phases. Two components work with every phase: the symbol table (stores names and attributes) and the error handler (reports errors with line numbers).

MermaidDiagram
Rendering diagram…

Running example: position = initial + rate * 60 where position, initial, rate are float.

Phase Task Output for the example
1. Lexical analysis Scans characters, groups them into lexemes and produces tokens; enters identifiers into the symbol table; removes whitespace and comments <id,1> <=> <id,2> <+> <id,3> <*> <num,60>
2. Syntax analysis Checks token order against the grammar and builds a parse/syntax tree Syntax tree (diagram below)
3. Semantic analysis Type checking, declaration checks, type conversions (coercion) 60 is int, rate is float, so insert inttofloat(60)
4. Intermediate code generation Produces machine-independent code, usually three-address code t1 = inttofloat(60)
t2 = id3 * t1
t3 = id2 + t2
id1 = t3
5. Code optimization Improves speed/size: constant folding, copy propagation, dead-code removal t1 = id3 * 60.0
id1 = id2 + t1
6. Code generation Selects instructions, allocates registers, emits target code LDF R2, id3
MULF R2, R2, #60.0
LDF R1, id2
ADDF R1, R1, R2
STF id1, R1

Input and output summary

  • Lexical analyzer: character stream to token stream.
  • Syntax analyzer: tokens to syntax tree.
  • Semantic analyzer: syntax tree to type-checked (annotated) tree.
  • Intermediate code generator: annotated tree to three-address code.
  • Optimizer: intermediate code to better intermediate code.
  • Code generator: optimized intermediate code to target code.

The first three phases form the analysis (front end); the last three form the synthesis (back end).

Syntax tree (phase 2)

MermaidDiagram
Rendering diagram…

Tree after semantic analysis (phase 3): the integer constant is converted to float.

MermaidDiagram
Rendering diagram…

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.