Graphics Program in C: Libraries, Code & Examples

Published: 31 Oct 2025 | Reading Time: 10 min read

Key Takeaways From The Blog

Introduction

Many C learners dream of creating programs that go beyond plain text — they want to build visuals, animations, or even simple games.

Yet, most beginners get stuck while setting up libraries, linking drivers, or figuring out how graphics functions actually work.

This blog simplifies the process. You'll learn how to write your first graphics program in C, and explore essential libraries like graphics.h, SDL, and OpenGL, and gradually move from basic 2D drawings to interactive visuals. By the end, you'll have a clear roadmap to turn plain C code into visual creativity.

What is the Graphics Program in C

Computer graphics programs in C allow developers to create visual elements such as shapes, lines, and images using libraries like OpenGL, Allegro, and GDI. These programs make graphics in C more versatile, enabling developers to design both 2D and 3D visuals efficiently. It's a blend of creativity and technical skill, requiring a solid grasp of programming fundamentals and experience with development environments such as Code::Blocks or Visual Studio. The uses range across gaming, computer-aided design and drafting, data visualisation, multimedia, interface design, animation, and special effects.

Libraries of Graphic Program in C

A graphics program in C relies on libraries that simplify drawing and rendering. These graphics functions in C help you create lines, circles, and animations efficiently. Here are some of the most popular ones:

graphics.h

A simple C library for basic 2D graphics, including shapes and lines. It is perfect for beginners learning graphics programming. It's easy to use but lacks support for modern graphics and 3D rendering. It mainly works with older compilers, such as Turbo C++.

OpenGL

Strong and comprehensive C graphics library that allows the creation of the best 3D graphics. It offers an enormous range of tools for rendering 3D objects and developing interactive applications.

Simple DirectMedia Layer (SDL)

A multimedia cross-platform library built at the low level of hardware access meant for Direct3D, OpenGL, audio, keyboard, mouse, joystick, 2D graphic drawing, and graphical output. It is mainly used to create games and multimedia applications.

Allegro

Allegro is a relatively simple multimedia library for C/C++ that supports graphics, sound, and input devices, making it suitable for 2D game development.

GTK+ (GIMP Toolkit)

An object-oriented free software Development toolkit that can be used in making GUIs.

Cairo

The best and probably the only fit is a vector graphics library that provides high-quality 2D graphics. Compatible with several output types, including PNG, PDF, and SVG, it is appropriate for both web graphics and print.

SFML (Simple and Fast Multimedia Library)

The software library that can be incorporated into the formation of 2D/3D games and other multimedia products. It comes with simple interfaces for drawing graphics, controlling sounds, and managing input gadgets.

GLUT (OpenGL Utility Toolkit)

An OpenGL library that helps create the window, input, and 3D graphics, which makes it easier to produce cross-platform applications.

Qt

A highly effective GUI platform for building graphical and haptic-based interfaces for desktops and mobile devices.

DISLIN

A powerful graphics library for data visualisation. It is mainly used for scientific plotting and engineering applications. It supports various chart types, 2D/3D plots, and file export formats. It's important to know that it's more focused on visualising data than on real-time rendering. Therefore, it is unsuitable for interactive graphics or game development.

GLFW

A lightweight library for creating OpenGL-based 3D graphics applications. It handles window creation, input, and context management; therefore, it's great for modern game development and simulations. However, it doesn't offer built-in GUI widgets or high-level graphics functions, so advanced features require additional libraries.

Setting Up Modern Graphics Libraries

If you want to do advanced graphics programming, consider using modern libraries like OpenGL or SDL.

OpenGL Setup

SDL (Simple DirectMedia Layer) Setup

Common Setup Issues

By properly setting up your graphics environment, you can smoothly transition to writing and running graphics programs in C, whether you use classic libraries like graphics.h or modern options like OpenGL and SDL.

Bottom Line: A small configuration effort upfront avoids big headaches when you start writing a graphics program in C.

Colors of C Language Graphics

Colours play an essential role in any graphics program in C, adding vibrancy and depth to the visuals created through graphics functions, such as setcolor() and floodfill(). Graphics libraries in C offer functions that manipulate and apply colours to the output. The most widely used scheme in C is the RGB (Red, Green, Blue) model.

RGB Color Model

In the RGB colour model, every colour is made by combining red, green, and blue values. Each value ranges from 0 to 255, where 0 is no intensity and 255 is full intensity. For instance, red is represented by (255, 0, 0), green by (0, 255, 0), and blue by (0, 0, 255). Combining these values lets you create millions of unique colours for vibrant visuals. Many graphics libraries also offer predefined colour constants to simplify implementation.

Setting Colors in C

You can set the colour of graphical elements using functions from the graphics library. For instance, in the graphics.h library, the setcolor() function sets the drawing color. To set the colour to red, you use:

setcolor(RED);

Once set, the subsequent graphical elements will be drawn in red. You can also create custom colours by specifying RGB values. For example, to create purple:

setcolor(COLOR(128, 0, 128));

It mixes red and blue to generate purple.

Predefined Color Constants

Color Macro Integer Value
BLACK (0, 0, 0)
BLUE (0, 0, 255)
GREEN (0, 255, 0)
CYAN (0, 255, 255)
RED (255, 0, 0)
MAGENTA (255, 0, 255)
BROWN (165, 42, 42)
LIGHT GRAY (211, 211, 211)
DARK GRAY (169, 169, 169)
LIGHT BLUE (173, 216, 230)
LIGHT GREEN (144, 238, 144)
LIGHT CYAN (224, 255, 255)
LIGHT RED (255, 160, 160)
LIGHT MAGENTA (255, 182, 193)
YELLOW (255, 255, 0)
WHITE (255, 255, 255)

Syntax of Graphics Program in C

The general syntax structure for a graphics program in C using the graphics.h library looks like this:

Basic Structure Components

  1. #include <graphics.h>: Adds the graphics library for drawing functions.
  2. initgraph(&gd, &gm, NULL): Initializes graphics mode; gd detects the driver, gm sets the mode.
  3. Graphics Functions: Use functions like circle(), line(), or rectangle() to draw shapes.
  4. getch(): Waits for a key press before exiting.
  5. closegraph(): Closes the graphics mode and deallocates resources.

Basic Template

#include <graphics.h>  // Include the graphics library
#include <conio.h>     // For getch() function (optional)

int main() {
    int gd = DETECT, gm;  // Graphics driver and mode variables

    // Initialize the graphics mode
    initgraph(&gd, &gm, NULL);

    // Graphics functions to draw shapes or perform actions
    // Example: Drawing a circle
    circle(200, 200, 100);

    // Wait for user input before closing the window
    getch();

    // Close the graphics mode
    closegraph();

    return 0;
}

Quick note: In many graphics programs written in C, you use functions that draw shapes (lines, circles, rectangles) and you apply colours to them. For example, with graphics.h you might use setcolor(RED) or circle(x, y, r) to draw a red circle.

Basic Example of Graphics Program in C

Drawing A Circle

A basic graphics program in C involves setting up a graphics mode, drawing basic shapes, and then closing the graphics mode after the work is done. Below is a simple program that initializes the graphics mode and draws a circle:

#include <graphics.h>
#include <conio.h>   // For getch()

int main() {
    int gd = DETECT, gm;

    // Initialize graphics mode
    initgraph(&gd, &gm, NULL);

    // Draw a circle with center (300, 300) and radius 50
    circle(300, 300, 50);

    // Wait for user input before closing the window
    getch();

    // Close the graphics mode
    closegraph();

    return 0;
}

C Program to draw Circle, Triangle, Rectangle and Square

Here are C language graphics program examples for some basic shapes:

Program for Circle

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

int main(){
   int gd = DETECT,gm;
   int x ,y ,radius=80;
   initgraph(&gd, &gm, "C:\\TC\\BGI");
   /* Initialize center of circle with center of screen */
   x = getmaxx()/2;
   y = getmaxy()/2;

   outtextxy(x-100, 50, "CIRCLE Using Graphics in C");
   /* Draw circle on screen */
   circle(x, y, radius);

   closegraph();
   return 0;
}

Program for Triangle

#include <graphics.h>
#include <conio.h>

// Driver code
int main()
{
	// gm is Graphics mode which
	// is a computer display
	// mode that generates
	// image using pixels.
	// DETECT is a macro
	// defined in "graphics.h"
	// header file
	int gd = DETECT, gm;

	// initgraph initializes
	// the graphics system
	// by loading a graphics
	// driver from disk
	initgraph(&gd, &gm, "");

	// Triangle

	// line for x1, y1, x2, y2
	line(150, 150, 450, 150);

	// line for x1, y1, x2, y2
	line(150, 150, 300, 300);

	// line for x1, y1, x2, y2
	line(450, 150, 300, 300);

	// closegraph function closes
	// the graphics mode and
	// deallocates all memory
	// allocated by graphics system
	getch();

	// Close the initialized gdriver
	closegraph();
}

Program for Rectangle

// C program to draw a rectangle
#include <graphics.h>

// Driver code
int main()
{
	// gm is Graphics mode which is a computer display
	// mode that generates image using pixels.
	// DETECT is a macro defined in "graphics.h" header file
	int gd = DETECT, gm;

	// location of left, top, right, bottom
	int left = 150, top = 150;
	int right = 450, bottom = 450;

	// initgraph initialises the graphics system
	// by loading a graphics driver from the disk
	initgraph(&gd, &gm, "");

	// rectangle function
	rectangle(left, top, right, bottom);

	getch();

	// closegraph function closes the graphics
	// mode and deallocates all memory allocated
	// by the graphics system
	closegraph();

	return 0;
}

Program for Square

#include <graphics.h>
#include <conio.h>   // For getch()

int main() {
    int gd = DETECT, gm;

    // Initialize graphics mode
    initgraph(&gd, &gm, NULL);

    // Coordinates for the top-left corner and size of the square
    int x1 = 200, y1 = 200;  // Top-left corner
    int side = 150;           // Length of the side of the square

    // Draw a square using the rectangle function (same as a rectangle)
    rectangle(x1, y1, x1 + side, y1 + side);

    // Wait for user input before closing the window
    getch();

    // Close the graphics mode
    closegraph();

    return 0;
}

Program for 3D Bar Graph (Solid Bars)

#include <graphics.h>
#include <conio.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "");

    int height[] = {100, 150, 80, 200}; // Heights of bars
    int x = 50;

    for (int i = 0; i < 4; i++) {
        setfillstyle(SOLID_FILL, i+1); // Solid color fill
        bar3d(x, 300-height[i], x+50, 300, 20, 1); // Draw 3D bar
        x += 70;
    }

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

Program for Bouncing Ball Animation

#include <graphics.h>
#include <conio.h>
#include <dos.h>

int main() {
    int gd = DETECT, gm;
    int x = 50, y = 50, dx = 5, dy = 5, r = 20;

    initgraph(&gd, &gm, "");

    while (!kbhit()) { // Loop until key pressed
        cleardevice();
        circle(x, y, r);
        x += dx;
        y += dy;

        if (x + r > getmaxx() || x - r < 0) dx = -dx;
        if (y + r > getmaxy() || y - r < 0) dy = -dy;

        delay(50); // Control speed
    }

    closegraph();
    return 0;
}

Program for Sine Wave

#include <graphics.h>
#include <conio.h>
#include <math.h>

int main() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "");

    int midy = 200;

    for (int x = 0; x < 640; x++) {
        int y = midy + 100 * sin(x * 3.14 / 180); // Convert degrees to radians
        putpixel(x, y, WHITE); // Draw pixel
    }

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

Graphics Example Using Colours of C Language Graphics

A Coloured Circle and a Rectangle

#include <graphics.h>
#include <conio.h>

int main() {
    int gd = DETECT, gm;

    // Initialize graphics mode
    initgraph(&gd, &gm, NULL);

    // Set color and draw a circle
    setcolor(RED);
    circle(200, 200, 100);

    // Set color and draw a rectangle
    setcolor(BLUE);
    rectangle(150, 150, 250, 250);

    // Wait for user input
    getch();

    // Close graphics mode
    closegraph();

    return 0;
}

Advanced Graphics Programs in C

As you master the basics of graphics programming in C, you can explore more complex projects such as animations, screen savers, and drawing custom figures or text. These advanced graphics programs require a deeper understanding of the graphics environment and introduce you to concepts critical for modern visual applications.

Animations and Screen Savers

Animation in C typically involves updating graphics in real-time by repeatedly clearing and redrawing shapes to create motion. For example, you might animate a bouncing ball or a moving object by updating its position within a loop. To achieve smooth animation, you must manage the graphics mode and screen resolution carefully, ensuring your program adapts to the capabilities of the graphics drivers.

Screen savers are another classic example of advanced graphics programs. They often display random shapes, colours, or images across the screen, requiring the use of randomisation, timing functions, and the efficient use of the initgraph function to initialise graphics mode. The closegraph function should always be called at the end to release resources and return to text mode.

Drawing Custom Figures and Text

Advanced graphics programming goes beyond basic shapes. You can use algorithms to draw custom figures or render text with unique styles. Some programs implement image processing algorithms that manipulate pixel data directly, enabling effects such as blurring, edge detection, and custom pattern generation. Techniques like texture mapping let you apply intricate patterns or images onto shapes for more realistic visuals, especially when using modern graphics libraries.

Leveraging Modern Graphics Libraries

While graphics.h is suitable for learning, modern graphics libraries such as OpenGL and SDL provide greater control and advanced features. These libraries support complex rendering techniques, including lighting (to simulate realistic shadows and highlights) and advanced pipeline management. With these tools, you can achieve high-quality animations, real-time rendering, and interactive graphics at various screen resolutions.

Debugging and Performance

Advanced graphics programs often involve debugging low-level graphics code, especially when working closely with hardware or optimising performance. Issues may arise from improper use of the initgraph or closegraph functions, incorrect configuration of graphics drivers, or inefficient management of the rendering pipeline. Understanding these components is crucial for building robust, high-performance graphics applications.

Bottom Line: At this stage, you're building systems, not just demos. Your program becomes a product in its own right.

Applications of Graphics Programming in C

  1. Game Development: Graphic programming is essential for games, as it enables the development of 2-D and 3-D graphics and the implementation of interactivity.

  2. Computer-Aided Design (CAD): In CAD applications, graphics programming is used to model and control 2D and 3D objects.

  3. Data Visualisation: Graphics programming transforms data into graphical information such as charts, graphs, or diagrams.

  4. Image Processing: C for graphics programming helps in activities such as image Enhancement, Filtering and manipulation.

  5. Graphical User Interfaces (GUIs): Graphic programming involves developing interactive, user-friendly interfaces for software programs.

  6. Simulations and Visualisations: It creates simulations and visualises real-world situations using physical simulation, scientific simulations, and more.

  7. Embedded Systems: Graphics programming is used in embedded systems to deliver practical graphical user interfaces and inputs for devices such as smart appliances and medical instruments.

Pros and Cons of Graphics Program

Here are some of the pros and cons of graphics programs in C:

Pros

Cons

Conclusion

Learning C for graphics is fundamental to understanding how things work at the most basic level. Graphics programming is included in the curriculum for the initial-level software developer to increase their versatility and expand the field of application. For instance, game development, simulation, and user interface applications all use graphic programming. Knowledge of the structure and methods for creating object-oriented images enhances developers' ability to develop more effective applications. To learn more and build a strong foundation, you can enrol in the CCBP Academy 4.0 program to become job-ready.

Why It Matters

Understanding how to write a graphics program in C shows that you know not merely data processing but visual programming — a skill that strengthens your versatility as a developer. Whether you're building simulation tools, games, or data-driven visuals, your ability to handle graphics in C sets you apart.

Practical Advice for Learners

Frequently Asked Questions

What is graphics programming in C?

Graphics programming in C involves using libraries like OpenGL and SDL to create visual elements, shapes, and animations in software applications. It enables the development of interactive interfaces, games, and simulations.

What are the standard graphics libraries in C?

Shared graphics libraries in C include OpenGL, SDL, Allegro, and GTK+. These libraries provide tools for rendering 2D and 3D graphics, handling user input, and developing multimedia applications.

Do I need a special compiler for graphics programming in C?

Yes, to use graphics libraries like graphics.h, you may need a compiler that supports these libraries, such as Turbo C++ or Code::Blocks. Additionally, ensure you have the appropriate graphic library files set up in your IDE.

What is the difference between a circle and a rectangle in graphics programming?

In graphics programming, a circle is drawn using a centre point and radius, while its top-left and bottom-right corners define a rectangle. Both shapes are fundamental to building more complex graphics.

Can I use graphics programming for game development in C?

Yes, graphics programming is widely used in game development for rendering 2D and 3D environments, characters, and special effects. Libraries like SDL and OpenGL are popular choices for building interactive games in C.


Related Articles


Contact Information:

About NxtWave: NxtWave offers comprehensive technology education programs including NxtWave Academy and NxtWave Intensive to help students become job-ready with industry-recognized certifications.