ITM102 Structured Programming in C

Structured Programming in CUnit 910 min read

Graphics Programming in C: Initialization, Modes, Functions & Drawing

Unit 9 of Structured Programming in C covers graphics programming basics in C, including graphics initialization, supported modes, core graphics functions (lines, circles, pixels), and practical applications like drawing shapes, animations, and simple games using the graphics.h library.

TAKEAWAYS:

  • Graphics initialization in C requires including graphics.h and initializing the graphics mode using initgraph() with a driver and mode.
  • Three common graphics modes are TEXT, CGA (320×200), and VGA (640×480)—each with different resolutions and color capabilities.
  • Core graphics functions include line(), circle(), rectangle(), pixel(), and setcolor() to draw shapes and manipulate colors.
  • Coordinate systems in C graphics use (0,0) at the top-left corner, unlike math conventions.
  • Practical applications include game development (e.g., simple Pong), data visualization (e.g., bar charts), and animations (e.g., moving objects).
  • Always close the graphics mode with closegraph() to free resources and avoid memory leaks.

1. Introduction to Graphics Programming in C

Graphics programming in C allows developers to create 2D drawings, animations, and simple games using the graphics.h library (part of Turbo C/C++). This unit focuses on:

  • Initializing the graphics environment.
  • Understanding supported graphics modes.
  • Drawing basic shapes (lines, circles, rectangles).
  • Manipulating colors and pixels.

Why is this useful? Graphics programming is foundational for game development, data visualization, and interactive applications. Even simple programs like a digital clock with moving hands or a traffic light simulator rely on these concepts.


2. Graphics Initialization in C

Before drawing anything, the graphics environment must be initialized using initgraph(). This function requires:

  • A graphics driver (e.g., DETECT for auto-detection).
  • A graphics mode (e.g., VGAHI for high-resolution VGA).

Syntax:

#include <graphics.h>
#include <stdio.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
    // Graphics code here
    closegraph();
    return 0;
}
  • gd = DETECT → Automatically detects the best available graphics driver.
  • gm → Stores the selected graphics mode.
  • "C:\\TURBOC3\\BGI" → Path to the BGI (Borland Graphics Interface) directory (varies by system).

What happens when initgraph() is called?

flowchart TD
    A["initgraph(&gd, &gm, \"path\")"] --> B["Detects graphics hardware"]
    B --> C["Loads appropriate driver"]
    C --> D["Sets resolution & color mode"]
    D --> E["Initializes video memory"]
    E --> F["Returns success/failure"]

3. Graphics Modes in C

Graphics modes define resolution, color depth, and memory usage. Common modes include:

Mode Description Resolution Colors Memory Usage
TEXT Text-only mode (no graphics) N/A N/A Low
CGAHI High-resolution CGA (monochrome) 640×200 2 (black/white) Low
VGAHI High-resolution VGA 640×480 16 Medium
VGAMED Medium-resolution VGA 320×200 256 Low

Example:

initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Auto-detects best mode
// OR force a specific mode:
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Then set gm = VGAHI;

4. Core Graphics Functions

(A) Drawing Lines and Shapes

Function Syntax Example
line(x1,y1,x2,y2) Draws a line from (x1,y1) to (x2,y2) line(100,100,300,100);
circle(x,y,r) Draws a circle at (x,y) with radius r circle(200,200,50);
rectangle(x1,y1,x2,y2) Draws a rectangle rectangle(50,50,250,250);
pixel(x,y,color) Sets a single pixel at (x,y) pixel(100,100,RED);

(B) Setting Colors

setcolor(RED);   // Sets drawing color to red
setbkcolor(BLUE); // Sets background color to blue

Available colors (from graphics.h): BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY, LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE


5. Coordinate System in C Graphics

Unlike math (where (0,0) is at the bottom-left), C graphics use:

  • (0,0) at the top-left corner.
  • x increases rightward.
  • y increases downward.

Example:

line(100,100,300,100); // Draws a horizontal line at y=100
line(200,100,200,300); // Draws a vertical line at x=200

Visualization:

![cartesian coordinate system](/media/7ae3bffb93150e950fee.png "Coordinate system in C graphics (top-left origin) (Image: K. Bolino, Public domain, via Wikimedia Commons)")

6. Worked Example: Drawing a House

Let’s draw a simple house using graphics functions.

Code:

#include <graphics.h>
#include <stdio.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

    // Draw the house
    setcolor(RED);
    rectangle(100, 100, 300, 300); // Walls
    line(150, 100, 250, 50);       // Roof (triangle)
    line(150, 100, 150, 50);
    line(250, 100, 250, 50);

    // Draw a door
    setcolor(BLUE);
    rectangle(200, 200, 250, 300);

    // Draw a window
    setcolor(GREEN);
    rectangle(120, 150, 170, 200);

    getch(); // Wait for key press
    closegraph();
    return 0;
}

Step-by-Step Execution:

Step Action Visualization
1 Initialize graphics Empty screen
2 Draw rectangle (walls) House walls
3 Draw roof (triangle) House with roof
4 Draw door (blue rectangle) House with door
5 Draw window (green rectangle) Complete house

7. Real-World Applications

(A) eSewa: Transaction Confirmation Animations

  • When you pay via eSewa, the app shows a loading spinner (a rotating circle).
  • How it works:
    • A loop continuously redraws a circle at different angles using circle() and delay().
    • Example:
      for (int angle = 0; angle < 360; angle++) {
          setcolor(RED);
          circle(200, 200, 50);
          delay(50); // Pause for 50ms
          cleardevice(); // Clear screen
      }
      

(B) Pathao: Ride Allocation Visualization

  • Pathao’s backend uses simple graphics to simulate driver-rider matching on a map.
  • How it works:
    • A 2D grid represents the city.
    • pixel(x,y,RED) marks the rider’s location.
    • circle(driver_x, driver_y, 10) shows nearby drivers.
    • Example:
      pixel(100, 150, RED);   // Rider at (100,150)
      circle(120, 140, 10);   // Driver at (120,140)
      

(C) NTC: Traffic Light Simulation

  • The Nepal Traffic Company (NTC) could use C graphics to simulate traffic light timings.
  • How it works:
    • Three circles (red, yellow, green) are drawn.
    • A loop changes their colors every 5 seconds using setfillstyle().
    • Example:
      setfillstyle(SOLID_FILL, RED);
      floodfill(200, 100, RED); // Fill red light
      delay(5000);
      setfillstyle(SOLID_FILL, GREEN);
      floodfill(200, 200, GREEN); // Fill green light
      

8. Advanced: Drawing a Moving Object (Animation)

To create animation (e.g., a moving car), use a loop with delay() and cleardevice().

Code: Moving Car

#include <graphics.h>
#include <stdio.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");

    int car_x = 0;
    while (car_x < 640) {
        cleardevice(); // Clear screen
        setcolor(RED);
        rectangle(car_x, 200, car_x + 50, 250); // Car body
        line(car_x + 25, 200, car_x + 25, 220);   // Wheel
        line(car_x + 35, 200, car_x + 35, 220);   // Wheel
        car_x += 5; // Move car right
        delay(50);  // Pause
    }

    getch();
    closegraph();
    return 0;
}

Step-by-Step Animation:

flowchart LR
    A["Initialize graphics"] --> B["Draw car at x=0"]
    B --> C["Delay 50ms"]
    C --> D["Clear screen"]
    D --> E["Draw car at x=5"]
    E --> C

9. Common Mistakes & Debugging

Mistake Cause Fix
Graphics not displaying Wrong BGI path or driver not found Check path: "C:\\TURBOC3\\BGI"
Colors not working setcolor() called after initgraph() Call setcolor() before drawing
Program crashes on initgraph() Unsupported graphics mode Use DETECT or test VGAHI
Shapes not appearing Coordinates out of bounds Ensure (x,y) is within 0-639 (VGA)

10. Exam Tip

What examiners look for:

  1. Correct initialization (initgraph() with proper path).
  2. Accurate function usage (e.g., line(x1,y1,x2,y2) not line(x,y)).
  3. Proper coordinate handling (remember (0,0) is top-left!).
  4. Resource cleanup (always use closegraph()).
  5. Logical flow (e.g., setting color before drawing).

Common exam questions:

  • "Define initgraph() and explain three graphics modes." → Cover TEXT, CGAHI, VGAHI.
  • "Write a program to draw a circle and a line." → Use circle() and line() with correct syntax.
  • "How would you animate a moving object?" → Use cleardevice() + delay() in a loop.

Sample Answer for a 5-mark question:

*"Graphics initialization in C is done using initgraph(&gd, &gm, "path"), where gd is the graphics driver (e.g., DETECT) and gm is the mode (e.g., VGAHI). Three common modes are:

  1. TEXT: No graphics, text-only.
  2. CGAHI: 640×200 resolution, 2 colors.
  3. VGAHI: 640×480 resolution, 16 colors. The closegraph() function must be called to free resources."*

Final Note: Graphics programming in C is simple but powerful for visual applications. Master the basics (initgraph(), line(), circle()), and you can build games, simulations, and animations—even if they’re basic! Practice drawing shapes and animating objects to prepare for exams.

Based on the TU BITM syllabus for Structured Programming in C (ITM102), unit 9.

Discussion

Loading…