Previous year question · 2024
Final Examination 2024 (12th Batch) — Full Solution
JnU B.Sc. in CSE — 4th Year 1st Semester, Final Examination 2024 (12th Batch, Solved)
Eight questions from the Jagannath University B.Sc. in CSE 4th Year 1st Semester Final Examination 2024 (CSE-4105, 12th Batch) — full worked solutions covering computer graphics fundamentals and drivers, raster vs vector graphics with advantages and disadvantages, display hardware and application areas, the DDA algorithm traced for , the Mid-point circle algorithm derived and traced for radius at center , decision variables and mid-point coordinates for both E and SE choices in the midpoint circle, 2D and 3D translation in homogeneous matrix form, homogeneous coordinates and conversion of the translation matrix, 2D rotation of by and 3D rotation with equations/matrices/figures, parallel vs perspective projection with equations and figures, one/two/three-point vanishing points, the RGB color model with advantages/disadvantages, RGB-to-CMY conversion and CMY uses, Z-buffer placement of four polygons on a pixel grid with depth range , the Cohen-Sutherland line clipping algorithm and viewport definition, Sutherland-Hodgman polygon clipping of pentagon ABCDE, the basic scan-fill polygon algorithm and interior pixel convention, Bezier vs B-spline curves, the Z-buffer algorithm with a worked two-polygon example, illumination vs shading model, halftone approximation, linear vs non-linear multimedia, entropy calculation for an alphabet , lossless vs lossy compression, and Huffman coding for the string AABABBBBEBECCCCCDDD.
Question 1 — Computer Graphics Fundamentals, Raster vs Vector, Display Hardware & Applications
(a) What is computer graphics? Write some drives for introducing computer graphics. [1+3]
(b) Define and differentiate vector and raster graphics. What are the advantages and disadvantages of vector and raster graphics? [3+2]
(c) Briefly discuss about display hardware used in computer graphics. What are the common application areas of computer graphics? [3+2]
Concept Needed
Computer graphics is the discipline of generating, manipulating, storing and displaying visual content with computers. The field spans low-level pixel rasterization and high-level scene modeling. Two storage models — raster (pixel-based) and vector (geometry-based) — define the fundamental trade-off in image representation, and the display hardware layer (CRT → LCD → LED → OLED) carries the framebuffer to the viewer's eye.
(a) Definition and Drivers
Definition. Computer graphics is the branch of computer science concerned with the creation, manipulation, storage, and display of images, models, and visual information using computers. It includes everything from low-level pixel rasterization to high-level scene modeling, animation, and rendering.
Drivers (why computer graphics matters):
- Better visual communication — graphics convey information faster and more clearly than text; charts, diagrams, and animations help users interpret complex data quickly.
- User-interface enhancement — modern operating systems and applications rely on GUIs (windows, icons, menus, pointers), making computers accessible to non-technical users.
- Realistic simulation and training — flight simulators, medical training, military drills, and driving simulators provide safe, cost-effective practice environments.
- Entertainment industry — movies (CGI, VFX), video games, animations, and VR/AR content depend entirely on computer graphics.
- Scientific visualization — researchers visualize molecular structures, weather patterns, astronomical data, and fluid dynamics that would otherwise be impossible to observe.
- Computer-aided design (CAD/CAM) — engineering, architecture, and product design use graphics to model, simulate, and analyze designs before physical production.
- Medical imaging — CT, MRI, and ultrasound rely on graphics techniques to construct 3D views of internal body structures for diagnosis.
(b) Raster vs Vector Graphics
Raster graphics (bitmap): images composed of a fixed grid of pixels, each storing a color value. Resolution is fixed; zooming causes pixelation.
Vector graphics: images defined by mathematical equations, geometric primitives (points, lines, curves, polygons), and their attributes (color, fill, stroke). Resolution-independent — scales infinitely without quality loss.
| Aspect | Vector Graphics | Raster Graphics |
|---|---|---|
| Definition | Mathematical formulas / geometric primitives | Grid of pixels, each with a discrete color |
| Storage size | Smaller — only stores equations | Larger — stores per-pixel data |
| Scalability | Resolution-independent — no quality loss on zoom | Resolution-dependent — pixelation on zoom |
| Best for | Logos, icons, fonts, technical drawings | Photographs, realistic images, textures |
| Editing | Easy to edit individual shapes | Difficult to edit at pixel level |
| File formats | SVG, EPS, PDF, AI | BMP, JPEG, PNG, GIF, TIFF |
| Processing | Requires rendering calculations | Direct pixel manipulation |
| Photorealism | Difficult to achieve | Excellent |
Vector — Advantages: resolution-independent; small file size for simple art; easy object-level editing; precise geometric shapes; ideal for CAD and print. Vector — Disadvantages: unsuitable for complex photographic content; rendering can be slow for highly detailed scenes; limited photorealism.
Raster — Advantages: excellent for realistic images; simple capture from cameras and scanners; fast pixel-level operations (filters, color correction). Raster — Disadvantages: quality degrades on scaling; large file sizes at high resolution; memory intensive; per-pixel editing is tedious.
(c) Display Hardware & Application Areas
Display hardware translates the framebuffer (a raster image in GPU memory) into visible light on a screen.
- CRT (Cathode Ray Tube) — vacuum tube with electron guns that scan a phosphor-coated screen. Three guns for RGB. Now legacy.
- LCD (Liquid Crystal Display) — modulates a backlight through liquid crystal cells sandwiched between polarizers. Dominant in monitors and laptops.
- LED (Light Emitting Diode) displays — each pixel is an LED. Used in stadium displays, billboards, and modern TVs; LED can also refer to LED-backlit LCD panels.
- Plasma Display Panels (PDP) — small cells filled with ionized gas (plasma) that emit light when electrically stimulated. Historically important for large TVs.
- OLED (Organic LED) — self-emissive organic compounds; superior contrast, deeper blacks, flexible screens.
- Video cards / GPUs — dedicated hardware (NVIDIA, AMD) that performs parallel rendering, rasterization, and 3D acceleration.
- Display controllers — interface between CPU and display; manage the frame buffer (video memory) where pixel data is stored.
Common application areas:
- Computer-Aided Design (CAD) — engineering, architecture, mechanical design.
- Entertainment — movies, video games, animation.
- Education and training — e-learning, flight simulators, surgical simulators.
- Scientific visualization — meteorology, astronomy, biology, fluid dynamics.
- Medical imaging — CT, MRI, ultrasound visualization.
- Business — presentations, data visualization, dashboards.
- Virtual Reality (VR) and Augmented Reality (AR).
- Geographic Information Systems (GIS) — maps and terrain modeling.
Related Conceptual Questions
Q1.1. If a logo must appear both on a 1080p monitor and on a 5-meter outdoor banner, which format should you keep the master in?
A1.1. SVG (vector). A raster master at 1080p will pixelate when scaled to 5 meters; the SVG stores the logo as mathematical primitives that scale cleanly to any output size, including large-format print.
Q1.2. Why did LCDs replace CRTs for consumer computer displays, even though CRTs had excellent color and viewing angles?
A1.2. LCDs are thinner, lighter, draw less power, emit less heat, and have no burn-in risk. Manufacturing economies of scale also drove LCD panel prices far below CRT equivalents, ending the CRT's commercial life by the late 2000s.
Q1.3. Why are GPUs designed around rasterization rather than vector rendering at the hardware level?
A1.3. The framebuffer — the data the display actually reads — is inherently raster. Even vector formats (SVG, fonts, vector games) must be rasterized at display time. Building hardware around the final on-screen representation (pixels) avoids a redundant vector→raster step and lets the GPU pipeline specialize in massively parallel pixel ops.
(a) CG = creation, storage, manipulation, and display of images and visual information via computers. Drivers: better visual communication, GUI usability, simulation and training, entertainment, scientific viz, CAD, medical imaging.
(b) Raster = pixel grid; vector = mathematical primitives. (See table for full comparison.)
(c) Display hardware: CRT, LCD, LED, plasma, OLED, GPUs, display controllers. Application areas: CAD, entertainment, education, scientific viz, medical imaging, business, VR/AR, GIS.
For "drivers", pair each with a concrete use case — examiners reward application-grounded reasoning over generic platitudes.
Saying "vector graphics have higher resolution than raster." The correct phrasing is "resolution-independent" — vector images have no fixed resolution until they are rendered.
A 4K display = million pixels. DPI = dots per inch. Resolution = total pixel count (W × H). Pixel = smallest addressable dot on a raster display.
Question 2 — DDA Line Algorithm for (2,6)→(4,10) and Mid-Point Circle for r=3 at (4,4)
(a) Explain the DDA (Digital Differential Analyzer) algorithm and trace the algorithm for the given points to . [7]
(b) Derive the Midpoint circle algorithm. Considering the midpoint circle algorithm, draw a circle with radius and center . [7]
Concept Needed
The DDA algorithm is a line-drawing procedure based on calculating intermediate points along a straight line by sampling at unit intervals and computing from the line equation. It is simple but uses floating-point arithmetic and rounding. The midpoint circle algorithm is an integer-only rasterization method that exploits the 8-fold symmetry of circles — computing one octant and reflecting to obtain the other seven.
(a) DDA Algorithm — Theory
For a line from to , the slope is . Starting at , each successive point is sampled by stepping in the dominant direction:
where and , with .
Algorithm:
- Read the endpoints and .
- Compute , .
- Compute .
- Compute and .
- Initialize , , plot , .
- Repeat
stepstimes: , , plot , .
Disadvantages: uses floating-point arithmetic and rounding, so it is slower than Bresenham's integer-only algorithm.
(a) Trace for (2, 6) → (4, 10)
Given: , .
Step 1: Compute differences
Slope: .
Step 2: Compute steps and increments
Step 3: Tabulate
| Step | Round | Round | Plot | ||
|---|---|---|---|---|---|
| 0 | 2.0 | 6.0 | 2 | 6 | (2, 6) |
| 1 | 2.5 | 7.0 | 3 | 7 | (3, 7) |
| 2 | 3.0 | 8.0 | 3 | 8 | (3, 8) |
| 3 | 3.5 | 9.0 | 4 | 9 | (4, 9) |
| 4 | 4.0 | 10.0 | 4 | 10 | (4, 10) |
Generated points: .
(b) Mid-Point Circle Algorithm — Derivation
A circle of radius centered at the origin has the implicit equation:
Define the function:
- → inside the circle.
- → on the circle.
- → outside the circle.
Because a circle has 8-fold symmetry, we compute only one octant (start at , walk in / ) and reflect to obtain the other seven.
At each step from pixel we choose between:
- East (E):
- South-East (SE):
The mid-point between them is:
Decision parameter:
- → mid-point is inside the circle → choose East.
- → mid-point is on or outside the circle → choose South-East.
Recurrences (substituting ):
- If East chosen ( unchanged):
- If SE chosen ( decreases by 1):
Initial value at — substituting :
The integer-friendly form used in textbooks is — only the sign matters for the decision, so subtracting from every subsequent does not change any sign.
(b) Trace for radius 3 at center (4, 4)
For :
, so the first step is East. The center is then added at the end as .
With and updates at each iteration, starting from :
| Step | Decision | |||||
|---|---|---|---|---|---|---|
| Start | 0 | 3 | -2 | <0 → E | — | — |
| 1 (E) | 1 | 3 | 1 | ≥0 → SE | 3 | — |
| 2 (SE) | 2 | 2 | 2 | ≥0 → SE | — | -1 |
| 3 (SE) | 3 | 1 | 7 | ≥0 → SE | — | 5 |
Step-by-step:
- Start: , → E.
- Step 1 (E): , → SE.
- Step 2 (SE): , → SE.
- Step 3 (SE): , → SE.
- The next SE would drive to ; we stop at the boundary of the octant.
Octant-2 pixels (relative to center): .
Adding center : .
Full circle via 8-fold symmetry around — for each octant-2 pixel relative to the center, the eight reflected pixels are obtained by and , then adding the center :
| Octant-2 (relative) | Reflections (absolute, after adding center) |
|---|---|
| , and | |
| , plus (diagonal symmetry duplicates these) | |
| , plus |
Distinct boundary pixels (radius 3, center ): and the four corner pixels — 20 distinct boundary points forming the integer rasterization of the circle.
Related Conceptual Questions
Q2.1. Why is DDA slower than Bresenham's line algorithm in practice?
A2.1. DDA performs floating-point addition and rounding at every step. Bresenham avoids floats entirely by using an integer decision variable that is updated by small integer increments, making Bresenham faster on hardware without fast FPUs and equally accurate for the integer pixel grid.
Q2.2. Why does the midpoint circle algorithm compute only one octant?
A2.2. A circle has 8-fold symmetry across the horizontal, vertical, and both diagonal axes. Computing one octant (45°) and reflecting yields the other seven at zero extra cost — an 8× reduction in computation.
Q2.3. Why is the initial decision parameter acceptable when the true value is ?
A2.3. Only the sign of drives the next-step decision. Subtracting from every subsequent (which is what switching from to does) preserves every sign, so the algorithm produces the same output while keeping all values integer — a friendlier implementation.
(a) DDA: compute , , , . For : steps , , . Pixels: .
(b) Midpoint circle uses , updated by (East) or (SE). For at : octant-2 pixels relative to center are ; full ring via 8-fold symmetry around .
For tracing, lay out the recurrence constants once at the top (, for circle; for DDA), then tabulate — never recompute the constants at each step.
Mixing DDA's continuous stepping with the integer-only decision variable of Bresenham/midpoint. DDA = floats + rounding; midpoint = integer only.
DDA = simple, but slow (floats). Bresenham/midpoint = fast (integers only). Both algorithms for circle exploit 8-fold symmetry to save computation.
Question 3 — Decision Variables, 2D & 3D Translation, Homogeneous Coordinates
(a) Derive the equation for decision variable (both initial and new) for mid-point circle algorithm. Also derive the equations for calculating mid-point (both for E and SE). [3+3]
(b) What is Transformation? Calculate the 2-D and 3-D Translation equations and convert in matrix form. [1+4]
(c) Why homogeneous coordinates are used in transformation? Convert the derived matrix form of question no. 3(b) in homogeneous form. [3]
Concept Needed
A decision variable in the midpoint circle algorithm is an integer-only quantity whose sign tells the algorithm which neighbor pixel is closer to the true circle arc. The same idea underlies Bresenham's line algorithm. Translation is the rigid shift of an object by a vector — it is additive (not multiplicative) in plain coordinates but becomes a matrix multiplication once we adopt homogeneous coordinates, which is what enables a single composite matrix for any sequence of affine operations.
(a) Decision Variable Derivation (Mid-Point Circle)
For a circle centered at the origin with radius , define the implicit function:
- → inside the circle.
- → on the circle.
- → outside the circle.
For the first octant, increases and decreases. At step , the mid-point between the two candidates is:
The decision parameter is:
Initial decision parameter. Substituting (the first mid-point starting from ):
The integer form used in textbooks is .
Updated decision variable. Substituting and either (E) or (SE):
- East chosen (, unchanged):
- South-East chosen (, decreases by 1):
Mid-point coordinates for E and SE choices (used to evaluate the decision variable at the next step):
- East mid-point (between and ):
- South-East mid-point (between and ):
(b) Transformation & 2-D / 3-D Translation
Definition. A transformation is the process of modifying the coordinates, size, shape, or orientation of a graphical object. The four fundamental 2D transformations are translation, rotation, scaling, and reflection; in 3D we add shear and projection.
2-D translation. A 2-D point is moved by translation distances (along ) and (along ):
2-D translation matrix form:
3-D translation. A 3-D point is moved by translation distances :
3-D translation matrix form:
(c) Why Homogeneous Coordinates, and the Homogeneous Form of the Matrices
Why homogeneous coordinates are used:
- Unified matrix representation. In plain coordinates, translation is additive while rotation/scaling are multiplicative. In homogeneous form, every affine transformation becomes a single matrix multiplication.
- Composite transformations. Multiple sequential operations (e.g. scale → rotate → translate) collapse into a single composite matrix .
- Pipeline-friendly. Graphics pipelines (CPU vertex stage → GPU shader) expect (3D) or (2D) matrices for every operation; homogeneous form is the lingua franca.
- Hardware efficiency. GPU shader cores are built around matrix-vector multiplies; treating every transform uniformly simplifies the silicon.
2-D translation in homogeneous form. Append a third coordinate :
3-D translation in homogeneous form. Append a fourth coordinate :
In both forms, the bottom row (2D) or (3D) preserves the homogeneous coordinate so the result is a valid affine point.
Related Conceptual Questions
Q3.1. Why does the recurrence appear for the East case? Where does the come from?
A3.1. The new mid-point is . Subtracting the old mid-point from it in the implicit function gives . The -contribution cancels because does not change on an East step.
Q3.2. If translation is additive, why do we still convert it to a matrix?
A3.2. Without homogeneous form, you cannot fold translation into the same matrix that holds rotation and scaling, because matrix addition ≠ matrix multiplication. Homogeneous form turns translation into multiplication, so a long sequence (S, then R, then T) collapses into a single matrix product that the GPU applies in one pass.
Q3.3. Could we drop the bottom row of the homogeneous matrix and still get correct results?
A3.3. No — the bottom row is what preserves the coordinate, ensuring the output is an affine point rather than a homogeneous tuple. If the bottom row had other entries, the output would have and you'd need a perspective divide, which is the essence of perspective projection rather than affine translation.
(a) Initial: (true value ). New: (E) or (SE). Mid-points: , .
(b) Transformation modifies the coordinates/size/shape/orientation of an object. 2D translation: . 3D translation: . Both in column-vector additive form.
(c) Homogeneous form lets every affine transform be a matrix multiplication, enabling composite matrices and a uniform GPU pipeline. 2D: with in column 3. 3D: with in column 4.
When asked to "convert to homogeneous form," always preserve the bottom row as (2D) or (3D). Anything nonzero in that row turns the affine transform into a perspective projection.
Writing in the wrong order. "First S, then R, then T" means the composite is , with operations applied right-to-left.
Homogeneous coordinates make every affine transformation a matrix multiplication. Without them, translation is the odd one out (additive). The bottom row of an affine homogeneous matrix is always (2D) or (3D).
Question 4 — 2D Rotation, 3D Rotation, Projection Types, Vanishing Points
(a) What is rotation? Find the transformed point, , caused by rotating about the origin through an angle of . [1+2]
(b) Briefly explain 3-D rotation using appropriate equations, matrices and figures. [4]
(c) Explain about two types of projection with appropriate equations and figures. [4]
(d) What is vanishing point? Discuss about different types of vanishing points. [3]
Concept Needed
Rotation is the rigid transformation that moves a point around a pivot by an angle, preserving distance from the pivot. In 3D we rotate independently about each coordinate axis. Projection maps a 3D scene onto a 2D image plane — either with parallel rays (no foreshortening) or with rays converging at a finite center of projection (foreshortening and vanishing points).
(a) 2D Rotation about the Origin
Definition. Rotation is the transformation that moves a point along a circular arc around a fixed pivot by a specified angle , preserving the distance from the pivot.
Rotation matrix (counter-clockwise about the origin):
For and :
, .
So .
(b) 3D Rotation
3D rotation can occur about any of the three coordinate axes by angle .
About the X-axis (rotation in the YZ-plane; unchanged):
About the Y-axis (rotation in the XZ-plane; unchanged):
About the Z-axis (rotation in the XY-plane; unchanged — same as 2D rotation embedded):
Arbitrary 3D rotation is a composition of these: (or whichever order the textbook specifies, depending on whether the rotations are about world or moving axes).
(c) Two Types of Projection
1. Parallel Projection. Projection rays are parallel. Object size in projection is independent of distance from the projection plane.
- Orthographic (orthogonal): rays perpendicular to the projection plane. Front, top, side views.
- Oblique: rays at an angle to the projection plane.
- Cavalier: angle , foreshortening factor (true lengths preserved).
- Cabinet: angle , foreshortening factor .
where is the angle of the projector with the -axis and is the foreshortening factor.
In matrix form, parallel projection's last row is — the homogeneous coordinate is preserved, so no perspective divide occurs.
2. Perspective Projection. Projection rays converge at a finite center of projection (vanishing point). Objects appear smaller as they move farther from the viewer, producing realistic depth cues.
With the projection plane at and the center of projection at the origin:
In matrix form, the last row is nonzero — e.g. — which grows during projection; the final divide shrinks distant points, producing foreshortening.
| Aspect | Parallel Projection | Perspective Projection |
|---|---|---|
| Center of projection | At infinity (parallel rays) | At a finite point |
| Depth cue | No foreshortening | Foreshortening — far objects look smaller |
| Parallel lines | Stay parallel | Converge to vanishing points |
| Realism | Less realistic; CAD/engineering | Photorealistic; games, films |
| Matrix form | Last row | Last row has nonzero entries |
| Types | Orthographic, oblique (cavalier, cabinet) | One-point, two-point, three-point |
(d) Vanishing Points
Definition. A vanishing point is a point on the 2-D projection where lines that are parallel in 3-D space appear to converge. It is the projection of a point at infinity along a set of parallel lines, onto the image plane.
Types of vanishing points:
-
One-point perspective. One principal axis is perpendicular to the picture plane (the other two are parallel). All parallel depth lines converge to a single point. Example: looking down a straight hallway.
-
Two-point perspective. Two principal axes are at angles to the picture plane (none perpendicular). Two distinct vanishing points appear on the horizon line. Example: a corner view of a building.
-
Three-point perspective. All three principal axes make angles with the picture plane. A third vanishing point appears above or below the horizon. Example: looking up at a tall skyscraper from ground level.
Significance. Vanishing points create depth perception, enhance realism, and convey scale and distance in 2-D representations of 3-D scenes.
Related Conceptual Questions
Q4.1. Where does land after a rotation about the origin?
A4.1. rotated by becomes . Equivalently, rotated by lands at — the mirror image across the -axis of the answer.
Q4.2. Why does look "sign-flipped" compared to and ?
A4.2. In a right-handed coordinate system, the positive rotation about follows the left-hand rule relative to the axis, so the entry appears with opposite sign in the matrix. If you see sign errors, check the textbook's handedness convention.
Q4.3. Why do parallel 3D lines converge only in perspective projection, not in parallel projection?
A4.3. In parallel projection, the projection rays are themselves parallel — so two 3D parallel lines map to two 2D parallel lines. In perspective projection, all rays pass through a single finite center of projection, so two 3D parallel lines (not parallel to the image plane) trace two rays that meet at a single point in the image — the vanishing point.
(a) .
(b) 3D rotation matrices (above). Arbitrary 3D rotations are products of these.
(c) Parallel: rays parallel, last row , no foreshortening. Perspective: rays converge at a finite center, last row has nonzero entries, foreshortening present.
(d) Vanishing point: projection of a point at infinity on parallel 3D lines. One-point, two-point, three-point perspectives for 1, 2, or 3 principal directions.
For 3D rotations, remember that 's entry has opposite sign to the others in the standard right-handed formulation — this trips up most students.
Using the 2D rotation formula on a 3D point with non-zero . The 2D rotation only acts in the XY-plane; you need (or one of the other 3D matrices) for a true 3D rotation.
Euler angles, quaternions, and rotation matrices are three ways to encode 3D orientation. Matrices are intuitive; quaternions avoid gimbal lock and interpolate smoothly.
Question 5 — RGB & CMY Color Models, Z-Buffer with Four Polygons on a 6×6 Image
(a) What is color model? Describe RGB color model with advantages and disadvantages. [1+5]
(b) How to convert RGB color model to CMY color model? What are the uses of CMY color model? [1+2]
(c) Consider a Z-buffer with a range of to and pixel image and four polygons as follows: [5]
- Polygon 1: Depth ; vertex1 ; vertex2 ; vertex3 ; vertex4 .
- Polygon 2: Depth ; vertex1 ; vertex2 ; vertex3 ; vertex4 .
- Polygon 3: Depth ; vertex1 ; vertex2 ; vertex3 ; vertex4 .
- Polygon 4: Depth ; vertex1 ; vertex2 ; vertex3 ; vertex4 .
Now place the polygons using the Z-buffer method.
Concept Needed
A color model is a mathematical system for representing colors as tuples of numbers in a reproducible range. RGB is the additive model that maps directly to display hardware; CMY is the subtractive model used in printing. The Z-buffer (depth buffer) is the standard image-space hidden-surface algorithm: at each pixel, store the smallest depth seen so far, and write the corresponding polygon's color.
(a) RGB Color Model
Definition. A color model is a mathematical framework for representing colors as tuples of numbers (typically three or four components), with rules for combining those components into the visible spectrum.
RGB (Red, Green, Blue) is an additive color model: colors are produced by adding varying intensities of red, green, and blue light. Each component ranges from 0 to 255 in 8-bit storage.
- → Black (no light)
- → White (full intensity of all)
- → Red
- → Green
- → Blue
- → Yellow (R + G)
Advantages of RGB:
- Directly corresponds to how monitors, TVs, and other emissive displays produce color (each pixel has RGB sub-pixels).
- Wide gamut for emission-based displays.
- Easy hardware implementation — every modern display is built around three RGB sub-pixels.
- Intuitive for light-based color mixing.
- Efficient for digital cameras and scanners (sensors are RGB).
- Simple to manipulate in image editing software.
Disadvantages of RGB:
- Not perceptually uniform — equal numerical changes don't produce equal perceptual changes.
- Inefficient for printing (CMYK is needed).
- Channels are correlated — changing one channel affects the others.
- Difficult to specify a desired color directly without color-picker UI.
(b) RGB → CMY Conversion & Uses of CMY
Conversion. CMY is the subtractive model: each component is computed by subtracting the RGB intensity from full white:
assuming normalized RGB values in . For 8-bit RGB (0–255):
Uses of CMY:
- Color printing — primary model for inkjet and laser printers; CMYK extends with a dedicated black ink for deeper blacks.
- Photographic reproduction — used in film photography and print media.
- Packaging design — magazines, brochures, posters.
- Subtractive color mixing — when pigments are physically mixed, colors are subtracted from reflected white light, so CMY applies.
(c) Z-Buffer Method
Algorithm:
- Set the frame buffer to the background color.
- Initialize the Z-buffer with the maximum depth value ().
- For each polygon, for each pixel in the polygon's - projection:
- Compute the polygon's at .
- If , set and write the polygon's color to the frame buffer.
Polygons on the image (with depth range , smaller = closer to viewer):
| Polygon | Depth | Rectangle (vertices) | Pixels covered |
|---|---|---|---|
| P1 | 4 | rows 1–3, cols 1–3 | |
| P2 | 2 | rows 0–2, cols 3–5 | |
| P3 | 8 | rows 2–5, cols 2–4 | |
| P4 | 4 | rows 0–3, cols 2–5 |
Each polygon has a uniform scalar depth (constant across its pixels). The Z-buffer keeps the minimum at each pixel — the closest visible surface.
Final Z-buffer (each cell shows the minimum depth of all polygons covering it):
| y \ x | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 5 | 10 | 10 | 8 (P3) | 8 (P3) | 8 (P3) | 10 |
| 4 | 10 | 10 | 8 (P3) | 8 (P3) | 8 (P3) | 10 |
| 3 | 10 | 4 (P1) | 4 (P4) | 4 (P1, P4) | 4 (P3, P4) | 4 (P4) |
| 2 | 10 | 4 (P1, P4) | 8 (P1, P3, P4) | 2 (P2, P4) | 8 (P2, P3, P4) | 2 (P2) |
| 1 | 10 | 4 (P1, P4) | 4 (P1, P4) | 2 (P2, P4) | 2 (P2, P4) | 2 (P2, P4) |
| 0 | 10 | 10 | 4 (P4) | 2 (P2, P4) | 2 (P2, P4) | 2 (P2, P4) |
Note: at both P1 and P4 have depth 4 and P3 has depth 8 — minimum is 4. At and P1 and P4 share depth 4 (P3 also covers at depth 8). At P3 covers with depth 8 and P4 covers with depth 4 — minimum is 4.
Visibility result:
- P2 (depth 2) is the closest polygon; it dominates wherever its pixels overlap any other.
- P1 and P4 (depth 4) are visible only where P2 doesn't overlap.
- P3 (depth 8) is the farthest; it is fully covered wherever P1, P2, or P4 also cover. P3 is only visible in the strip rows 4–5, cols 2–4 where no other polygon reaches.
Related Conceptual Questions
Q5.1. Why is the Z-buffer called an "image-space" algorithm?
A5.1. It operates per-pixel in the final 2D image, not per-polygon in 3D object space. The Z-buffer is a 2D array indexed by screen coordinates, with one depth per pixel — the resolution of the algorithm is the display resolution, not the polygon count.
Q5.2. What is Z-fighting, and when does it occur?
A5.2. Z-fighting happens when two surfaces have nearly identical depths at the same pixel (e.g. coplanar polygons). Tiny rounding errors in the depth comparison cause one polygon or the other to win unpredictably, producing a flickering checkerboard pattern. Mitigations: nudge one polygon by a small , increase depth-buffer precision, or use depth bias.
Q5.3. Does RGB-to-CMY lose information?
A5.3. The mathematical conversion is lossless as long as both are stored at the same precision. In practice, print workflows quantize to ink coverage and add a separate K (black) channel in CMYK, so some saturation detail is approximated — but the underlying math is bijective.
(a) RGB is an additive color model with channels each in . Advantages: hardware match, simple, ecosystem. Disadvantages: not perceptually uniform, poor for print.
(b) , , . CMY is used for color printing, photography reproduction, packaging, and subtractive pigment mixing.
(c) P2 (depth 2) is closest; P3 (depth 8) is farthest; P1 and P4 (depth 4) sit in between. Pixels where P2 covers are written with depth 2; pixels where only P3 covers retain depth 8; the rest are at depth 4.
For Z-buffer problems, list every polygon's pixel rectangle first, then for each image cell find the minimum depth. Drawing a quick sketch with each polygon as a colored rectangle helps avoid arithmetic mistakes.
Treating "depth" as if larger means closer. The convention is usually smaller depth = closer; check the paper's wording (here "range to " is consistent with smaller = closer).
RGB = additive, display hardware. CMY(K) = subtractive, print. HSV = perceptual, color pickers. YUV/YCbCr = video. The Z-buffer stores the minimum depth seen so far at each pixel.
Question 6 — Viewport, Cohen-Sutherland Clipping, Sutherland-Hodgman Polygon Clipping, Scan-Fill
(a) Define viewport. Describe the basic idea of Cohen-Sutherland clipping algorithm. [1+3]
(b) Determine the clipped region for the following polygon ABCDE using Sutherland Hodgman polygon clipping algorithm. The rectangle signifies the viewport. [6]
(c) Write the basic scan-fill algorithm for polygon filling. What is interior pixel convention? [2+2]
Concept Needed
A viewport is the on-screen rectangle where the world-coordinate window is displayed. Clipping cuts away the parts of a scene outside the viewport. Cohen-Sutherland clips individual line segments using 4-bit outcodes; Sutherland-Hodgman clips polygons against a convex window by walking each vertex through each clipping edge. Scan-fill rasterizes a polygon by computing scanline intersections and filling between paired crossings; the interior pixel convention decides how to treat boundary pixels.
(a) Viewport & Cohen-Sutherland Clipping
Viewport. A rectangular region on a display device (in screen coordinates) where the contents of a window in world coordinates are mapped and displayed. It defines the visible area for output.
Cohen-Sutherland line clipping. Each line endpoint is tagged with a 4-bit outcode indicating which of nine regions it lies in, relative to the clipping rectangle:
| Bit | Region | Condition |
|---|---|---|
| 1 (Top) | Above the rectangle | |
| 2 (Bottom) | Below the rectangle | |
| 3 (Right) | Right of the rectangle | |
| 4 (Left) | Left of the rectangle |
The 9 regions and their codes:
| 1001 (top-left) | 1000 (top) | 1010 (top-right) |
|---|---|---|
| 0001 (left) | 0000 (inside) | 0010 (right) |
| 0101 (bottom-left) | 0100 (bottom) | 0110 (bottom-right) |
Algorithm:
- Compute outcodes for both endpoints of the line segment.
- Trivial accept: both outcodes are — both endpoints inside, draw the line.
- Trivial reject: bitwise AND of the two outcodes is non-zero — both endpoints share a side outside the rectangle, discard the line.
- Otherwise: the line crosses a boundary. Pick an endpoint that is outside, clip it against the boundary it crosses (top, bottom, left, or right) using the parametric line , , replace it with the intersection point, recompute its outcode, and repeat until trivial accept or reject.
The algorithm finds intersections iteratively, clipping against one boundary at a time, and is very efficient for scenes where most segments are either trivially accepted or trivially rejected.
(b) Sutherland-Hodgman Polygon Clipping of ABCDE
The Sutherland-Hodgman algorithm clips a polygon against a convex clipping window by sequentially clipping against each boundary (left, right, top, bottom). For each input edge :
| Output | ||
|---|---|---|
| Inside | Inside | |
| Outside | Inside | Intersection then |
| Inside | Outside | Intersection |
| Outside | Outside | (nothing) |
Reading the figure (from the source .tex): the viewport is the rectangle with corners roughly and . The polygon ABCDE has approximate vertices (from the figure):
The viewport is the inner rectangle. Walking the algorithm against each boundary:
- Left edge (): no vertex is left of the viewport — all are inside this axis. Output unchanged.
- Right edge (): no vertex is right of the viewport — all are inside. Output unchanged.
- Bottom edge (): is below (); is above (); are around the boundary (). Walking the polygon edge by edge and emitting intersections with where each edge crosses the line produces a clipped bottom contour.
- Top edge (): all vertices are below the top — no edge crosses. Output unchanged.
The final clipped polygon consists of the parts of the polygon inside the viewport, joined by intersection points where the polygon's edges crossed the bottom boundary.
Note: Because the source figure uses TikZ coordinates rather than integer pixel coordinates, exact pixel values of the intersection points depend on the precise vertex positions; the procedure above is the conceptual answer. The key point is that Sutherland-Hodgman clips against each boundary in turn, and the output list of one pass becomes the input of the next.
(c) Basic Scan-Fill Algorithm & Interior Pixel Convention
Basic scan-fill algorithm:
Details and edge cases:
- Intersection counting. For a non-self-intersecting polygon, the scanline crosses an even number of edges; pairs are .
- Vertex handling. A scanline passing through a vertex touches two edges at the same point; use the upper-endpoint rule — count the intersection if the vertex is the lower endpoint of an edge, but not if it is the upper endpoint (or use your textbook's specific convention consistently).
- Horizontal edges. Skip horizontal edges; they would otherwise produce duplicates at every pixel along the edge.
- Active-edge list (AEL). Real implementations maintain a sorted list of edges crossing the current scanline and update incrementally each scanline, avoiding a full recompute — this is how graphics libraries implement scan-fill efficiently.
Interior pixel convention. When a polygon boundary passes between two pixels, an interior pixel convention decides which pixels are considered part of the polygon and which are not.
Common conventions:
- Even-odd (parity) rule — count edge crossings along the scanline; a pixel is inside if the count is odd. Default for polygons with holes.
- Boundary-inclusive — pixels whose centers lie exactly on the boundary are filled in the polygon's color.
- Boundary-exclusive — boundary pixels are drawn separately (e.g. in black) and only strictly interior pixels get the polygon's color.
The choice affects how thick the polygon border looks and whether adjacent polygons share boundary pixels cleanly.
Related Conceptual Questions
Q6.1. Why use 4-bit outcodes instead of a single flag per endpoint in Cohen-Sutherland?
A6.1. A 4-bit outcode encodes which side the endpoint is on — top, bottom, left, right, or any combination. The trivial-reject test (bitwise AND of two outcodes) detects "both endpoints on the same outside side" in one operation; the trivial-accept test (both outcodes are ) handles "both endpoints inside" in another. A single flag would lose this directional information.
Q6.2. Can Sutherland-Hodgman clip against a circular viewport?
A6.2. No, not directly. Sutherland-Hodgman only works for convex clipping windows with straight edges. Although a circle is convex, the algorithm's per-edge intersection math assumes straight edges on the clipping window. For circular windows you'd need a different algorithm (Weiler-Atherton with circular boundary, or specialized ellipse/polygon clipping).
Q6.3. Why use floating-point arithmetic for scanline intersections when Bresenham uses integers for lines?
A6.3. Polygon edges can have arbitrary slopes, and the intersection with a horizontal scanline generally falls between integer positions. The exact intersection point is a real number; rounding it determines which pixel is "on" the boundary. Bresenham avoids floats because it uses a decision variable instead of computing intersection 's explicitly.
(a) Viewport = on-screen rectangle. Cohen-Sutherland: 4-bit outcodes per endpoint; trivial accept if both ; trivial reject if bitwise AND nonzero; otherwise clip against a boundary and iterate.
(b) Apply Sutherland-Hodgman edge by edge against the viewport. The output list of the last clipping pass is the clipped polygon.
(c) Scan-fill: per scanline, find intersections, sort, pair, fill. Interior pixel convention decides how boundary pixels are handled (even-odd, inclusive, exclusive).
For Cohen-Sutherland, when neither trivial accept nor trivial reject applies, clip one endpoint at a time. Don't try to clip both simultaneously.
Confusing Cohen-Sutherland's outcode AND test (used for trivial reject) with the OR test. AND detects "both outside same side" (nonzero); OR is not used here.
Cohen-Sutherland clips lines; Sutherland-Hodgman clips polygons; Liang-Barsky is a parametric alternative to Cohen-Sutherland that's often faster in practice. The Active Edge List (AEL) optimization makes scan-fill fast enough for real-time rendering.
Question 7 — Bezier vs B-Spline, Z-Buffer with Two Polygons, Illumination vs Shading, Halftone
(a) Enumerate the major differences between Bezier curve and the B-spline curve. [3]
(b) Explain the Z-buffer algorithm for hidden surface removal. Suppose we have two polygons A and B with Z values and . Assume pixel image and value of Z is from to . Find which polygon will be hidden and why? [5]
(c) Compare between Illumination and shading model. [3]
(d) What is Halftone approximation? [3]
Concept Needed
Curves are parametric representations: Bezier is simple but global in control; B-spline offers local control and independent degree choice. The Z-buffer is the standard image-space hidden-surface algorithm: store the smallest depth per pixel and write that polygon's color. Illumination models compute light intensity at a point; shading models distribute that color across a polygon surface. Halftoning simulates continuous tone on devices with few intensity levels (e.g. 1-bit printers).
(a) Bezier vs B-Spline Curve
| Aspect | Bezier Curve | B-Spline Curve |
|---|---|---|
| Definition | Single polynomial defined by control points | Piecewise polynomial defined by control points, knot vector, basis |
| Control | Global — moving any control point affects the whole curve | Local — moving one control point affects only a nearby region |
| Degree | Polynomial degree = number of control points − 1 | Polynomial degree is independent of number of control points |
| Endpoints | Curve passes through first and last control points | Curve generally does NOT interpolate any control point |
| Convex hull | Curve lies inside the convex hull of control points | Curve lies inside the convex hull |
| Continuity | C∞ inside the segment | Built-in continuity at knot boundaries (typically C²) |
| Modification | Harder — any change affects the whole curve | Easier — change one point, rest is undisturbed |
| Complexity | Simpler to derive and render | More complex math, but more flexible |
Rule of thumb: Use Bezier for simple, fixed shapes (UI icons, glyphs, one-off paths). Use B-spline (or NURBS) when you need fine control over complex, evolving shapes (animation paths, CAD models).
(b) Z-Buffer Algorithm + Two-Polygon Example
Algorithm.
Data structures:
- Frame buffer — stores color/intensity for each pixel (initialized to background).
- Z-buffer — stores the depth of the closest surface seen at each pixel (initialized to maximum depth).
Steps:
- Set the frame buffer to the background color.
- Initialize the Z-buffer to the maximum depth (here ).
- For each polygon:
- For each pixel in the polygon's projection:
- Compute the polygon's at .
- If , then this polygon is closer at this pixel: set and write the polygon's color to the frame buffer.
- For each pixel in the polygon's projection:
Advantages: simple; works for any number of polygons; hardware supported (GPU z-buffer); handles overlapping objects naturally. Disadvantages: memory-intensive (one depth per pixel); precision issues (z-fighting); no object coherence; resolution-dependent.
Worked example. image, Z range . Polygons A (Z = 0.7) and B (Z = 0.5).
With the convention "smaller = closer to viewer":
- Polygon B () is closer to the viewer.
- Polygon A () is farther.
At every pixel where both polygons project, the algorithm compares their depths:
- (initial)
- After scanning polygon A: at pixels where A projects.
- After scanning polygon B: at pixels where B projects, , so and B's color is written. At pixels where B does not project but A does, remains and A's color is shown.
Conclusion: Polygon A is hidden wherever polygon B projects to the same pixel. Polygon B is visible at all its own pixels. Polygon A is visible only where B does not project. B is in front; A is hidden behind B in their overlap.
(c) Illumination vs Shading Model
| Aspect | Illumination Model | Shading Model |
|---|---|---|
| Definition | Mathematical equations computing light intensity at a point on a surface | Method to apply illumination across an entire surface/polygon |
| Scope | Per-point / per-vertex calculation | Per-polygon / per-pixel application |
| Inputs | Light source(s), surface normal, view direction, surface properties | Result of illumination model + geometry |
| Output | Color / intensity at a specific 3D point | Color across the whole surface |
| Examples | Phong, Lambert, Blinn-Phong, Cook-Torrance | Flat shading, Gouraud shading, Phong shading |
| Speed | Generally fast | Gouraud/Phong shading slower but smoother |
| Purpose | Determine light-physics interaction | Distribute the computed color across the surface |
Key distinction: the illumination model computes the color at a point; the shading model distributes that color across the entire polygon using techniques like constant shading (flat), linear interpolation (Gouraud), or interpolated normals (Phong).
(d) Halftone Approximation
Definition. Halftone approximation is a technique used to simulate continuous-tone images on devices with limited color or gray-level capability (e.g. 1-bit black-and-white printers, early displays) by varying the density of black (or color) dots in a pattern.
Working principle:
- The image is divided into small cells (typically , , ).
- Each cell contains a fixed number of dots.
- The number of "on" dots in each cell approximates the local intensity.
- Bright regions → fewer dots; dark regions → more dots.
Types:
- Ordered dithering — uses a fixed threshold matrix (e.g. Bayer matrix).
- Error diffusion — distributes quantization error to neighboring pixels (e.g. Floyd-Steinberg).
Example — Bayer matrix (for 17 intensity levels):
For each pixel, compare its intensity (0–16) to : if the output dot is "on".
Applications:
- Newspaper printing.
- Low-color printers (1-bit black/white).
- Comic books.
- Image compression pre-processing.
- Display systems with limited color depth.
Advantages: reduces memory requirements; provides visual continuity; works with binary displays. Disadvantages: loss of fine detail; moiré patterns possible; visible dot structure.
Related Conceptual Questions
Q7.1. Why does B-spline use local control while Bezier does not?
A7.1. B-spline uses piecewise basis functions — each basis function has compact support, so moving one control point changes the curve only inside that support region. Bezier's Bernstein basis is global: every basis function has support over the whole interval , so any control-point move affects the whole curve.
Q7.2. Why does the Z-buffer work even when polygons overlap in complex ways?
A7.2. The Z-buffer operates per-pixel, independent of polygon order. For each pixel, only the polygon with the smallest depth at that pixel survives. This makes the algorithm immune to polygon overlap complexity — no sorting or ordering is required.
Q7.3. Why is flat shading faster than Gouraud shading?
A7.3. Flat shading computes the illumination model once per polygon and assigns the resulting color to every pixel in the polygon. Gouraud shading interpolates three vertex colors across the polygon, requiring extra work per pixel. Phong shading is slowest because it interpolates normals and recomputes the illumination model per pixel.
(a) Bezier: global control, degree = n − 1, interpolates endpoints. B-spline: local control, independent degree, approximates (does not interpolate) control points.
(b) Z-buffer stores smallest depth per pixel. B () is closer than A (); A is hidden wherever B projects to the same pixel.
(c) Illumination computes light at a point; shading distributes the result across a surface.
(d) Halftone simulates continuous tone on limited-depth devices by varying dot density in small cells.
For "Z = 0.7 vs 0.5" type questions, always state your convention first ("smaller Z = closer" or vice versa). The conclusion depends on it.
Calling Bezier and B-spline "the same thing." They are not — Bezier is global, B-spline is local; Bezier interpolates its endpoints, B-spline generally does not.
Bezier = simple, global. B-spline/NURBS = flexible, local. Z-buffer = per-pixel minimum depth wins. Illumination = physics; shading = distribution. Halftoning = dot density for binary displays.
Question 8 — Linear vs Non-Linear Multimedia, Entropy, Lossless vs Lossy Compression, Huffman Coding
(a) Find the differences between linear and non-linear multimedia. [3]
(b) What is Entropy in compression? Calculate the entropy for the followings Alphabet , and . [3]
(c) Write the differences between lossless and lossy compression techniques. [3]
(d) Let's assume we have a file to send containing the following values: AABABBBBEBECCCCCDDD. Generate the Huffman code to compress the file. [5]
Concept Needed
Linear multimedia plays sequentially with no user control (TV, cinema). Non-linear multimedia lets the user navigate freely (web pages, games, DVDs). Entropy is the theoretical lower bound on average bits per symbol — the Shannon limit. Lossless compression preserves every bit; lossy compression discards imperceptible detail. Huffman coding assigns shorter codes to more frequent symbols, producing an optimal prefix-free code for a known distribution.
(a) Linear vs Non-Linear Multimedia
| Aspect | Linear Multimedia | Non-Linear Multimedia |
|---|---|---|
| Definition | Content accessed sequentially with no user control | Content accessed in any order based on user choice |
| User navigation | None — passive viewing | Full user interactivity |
| Examples | TV broadcast, cinema film, radio | Websites, video games, DVDs, e-learning |
| Control | Determined by producer | Determined by user |
| Storage | Often streaming / broadcast | Stored and indexed |
| Tools | TV, projector | Computers, mobile devices |
| Use cases | Public information broadcast, mass entertainment | Interactive learning, gaming, training |
Linear: the user is a passive consumer. Time progresses without their control. Non-linear: the user decides what, when, and how to access content. Requires linking, search, and indexing.
(b) Entropy in Compression
Definition. Entropy is the average amount of information per symbol in a message. It represents the theoretical minimum number of bits needed to encode each symbol — the lower bound for lossless compression:
Calculation. Given alphabet with and :
Note: strictly, probabilities must sum to . We interpret the two values as the full distribution given in the question (and note the inconsistency).
Using the given probabilities as-is:
If we treat (the complement of for a proper two-symbol alphabet):
Either result is the entropy of the given source. The exact number depends on whether the question's is a typo for or an intentional incomplete distribution.
(c) Lossless vs Lossy Compression
| Aspect | Lossless Compression | Lossy Compression |
|---|---|---|
| Definition | Allows exact reconstruction of original data | Sacrifices some data for higher compression |
| Compression ratio | Lower (typically 2:1 to 4:1) | Higher (10:1 to 100:1+) |
| Quality | Identical to original | Reduced quality (often imperceptible) |
| Algorithms | Huffman, LZW, Run-Length, Arithmetic | JPEG, MPEG, MP3, Fractal, Wavelet |
| Use cases | Text files, executables, medical imaging, archives | Photos, video, audio (where minor loss acceptable) |
| Reversibility | Fully reversible | Not reversible |
| File formats | PNG, GIF, ZIP, FLAC | JPEG, MP3, MP4, MPEG |
| Criticality | Essential when exact data matters | Used when approximate is fine |
Examples.
- Lossless: ZIP archives, PNG images, source code, database backups, FLAC audio.
- Lossy: JPEG photos, MP3 audio, streaming video, voice calls.
(d) Huffman Coding for AABABBBBEBECCCCCDDD
Step 1: Count frequencies. Reading the string AABABBBBEBECCCCCDDD:
- A: positions 1, 2, 4 → 3
- B: positions 3, 5, 6, 7, 8, 10 → 6
- C: positions 13, 14, 15, 16, 17 → 5
- D: positions 18, 19, 20 → 3
- E: positions 9, 11 → 2
Total = 3 + 6 + 5 + 3 + 2 = 19 characters.
Step 2: Sort symbols by frequency (ascending).
| Symbol | Frequency |
|---|---|
| E | 2 |
| A | 3 |
| D | 3 |
| C | 5 |
| B | 6 |
Step 3: Build the Huffman tree.
- Iteration 1: Combine E (2) + A (3) → EA: 5.
- Iteration 2: Combine D (3) + EA (5) → DEA: 8.
- Iteration 3: Combine C (5) + B (6) → CB: 11.
- Iteration 4: Combine DEA (8) + CB (11) → Root: 19.
Step 4: Assign codes (0 to left child, 1 to right child at each internal node):
Step 5: Read off codes.
| Symbol | Frequency | Code | Length |
|---|---|---|---|
| D | 3 | 00 | 2 bits |
| C | 5 | 10 | 2 bits |
| B | 6 | 11 | 2 bits |
| E | 2 | 010 | 3 bits |
| A | 3 | 011 | 3 bits |
Verify the prefix property: no code is a prefix of another (, , , , — every leaf differs at the first differing bit). ✓
Step 6: Encode the string. AABABBBBEBECCCCCDDD:
Concatenated: 01101111011111111101011010101010000000 (43 bits).
Step 7: Compression statistics.
Total encoded bits:
For comparison, fixed-length coding with bits per symbol gives bits.
Compression ratio = . Space saved = .
Related Conceptual Questions
Q8.1. Why does entropy set a hard lower bound on lossless compression?
A8.1. Shannon's source coding theorem shows that any lossless code must use at least bits per symbol on average — otherwise, by the pigeonhole principle, two distinct messages would map to the same codeword and decoding would be ambiguous. So is the theoretical limit, and Huffman coding comes within 1 bit of it for symbol-by-symbol codes.
Q8.2. Why is the prefix property essential in Huffman codes?
A8.2. Without the prefix property, two different bit strings could be parsed in multiple ways during decoding, and the decoder could not tell which one the encoder meant. With the prefix property, reading bits from left to right, you can identify each symbol the moment you reach a leaf of the code tree — no separator between symbols is needed.
Q8.3. Can Huffman coding beat the entropy bound?
A8.3. No. Shannon's source coding theorem shows the average code length is at least for any uniquely decodable code. Huffman achieves the optimal symbol-by-symbol code (within 1 bit of for integer bit-lengths). To beat the bound you need block coding — encoding multiple symbols at a time — which then approaches asymptotically.
Q8.4. Is the Huffman code in (d) unique?
A8.4. Not strictly — different valid Huffman trees can be built by making different choices during the bottom-up merges (e.g. swapping the order of equal-frequency siblings). All such trees produce optimal (equal minimum total bits) codes, but the bit patterns assigned to each symbol differ. The code lengths in the table above are unique: the two rarest symbols (E, A) get 3-bit codes and the three more common ones (D, C, B) get 2-bit codes.
(a) Linear: sequential, no user control (TV, cinema). Non-linear: user navigates freely (web, games, DVDs).
(b) Entropy . For : bits/symbol. (If : bits/symbol.)
(c) Lossless: exact reconstruction, lower ratio (PNG, ZIP). Lossy: irreversible, higher ratio (JPEG, MP3).
(d) Frequencies: B=6, C=5, A=3, D=3, E=2. Codes: B=11, C=10, D=00, E=010, A=011. Encoded length: 43 bits vs 57 fixed-length — about saving.
When building a Huffman tree by hand, list the frequencies in ascending order at each step, combine the two smallest, and re-sort. Always re-sort after every merge — don't keep the new node in place just because it was just created.
Forgetting the prefix property when checking a code. A prefix-free code is uniquely decodable without separators between symbols. If any code is a prefix of another, the code is not uniquely decodable.
Entropy = theoretical limit. Huffman = practical optimal symbol code. Prefix property = unique decodability. Lossless vs lossy = exact vs approximate reconstruction.