Table of contents
1.
Introduction
2.
What is Graphics Program in C?
3.
Libraries of Graphic Program in C
4.
Colors of Graphics Program in C
5.
Syntax of Graphics Program in C
5.1.
C
6.
Applications of Graphics Program in C:
7.
Write a Program to Draw Animation Using Increasing Circles Filled with Different Colors and Patterns
8.
Program to Make a Screen Saver Displaying Different Size Circles Filled with Different Colors at Random Places
9.
Write a Program to Make a Moving Colored Car Using Inbuilt Functions
10.
Write a Program to Print Your Name in Hindi Script on Console Output in C
11.
Advantages of Graphics Program in C:
12.
Disadvantages of Graphics Program in C:
13.
Frequently Asked Questions
13.1.
What is the difference between graphics.h and other graphics libraries like OpenGL and SDL?
13.2.
Can I create 3D graphics using C programming?
13.3.
Is C the best language for graphics programming?
14.
Conclusion
Last Updated: Feb 4, 2025
Easy

Graphics Program in C

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Graphics programming in C is a way to create visual elements and animations using the C programming language. It allows you to draw shapes, lines, and other graphical elements on the screen. Graphics programming is used in many applications like video games, computer-aided design (CAD), and data visualization. 

Graphics Program in C


In this article, we will learn about the basics of graphics programming in C, like the libraries used, colors, syntax, and examples.

What is Graphics Program in C?

Graphics programming in C is a method of creating visual elements, such as shapes, lines, and images, using the C programming language. It involves using special libraries and functions to control the display of graphics on the screen. With graphics programming, you can create interactive and engaging programs that display visual information to the user.


In C, graphics programming is done using graphics libraries, which provide a set of functions and tools for drawing and manipulating graphical elements. These libraries handle the low-level details of interacting with the computer's graphics hardware, which makes it easier for programmers to create visual output.

Libraries of Graphic Program in C

To create graphics programs in C, you need to use special libraries that provide functions for drawing and manipulating graphical elements. There are several graphics libraries available for C, but the most commonly used ones are:

1. Graphics.h: This is the most basic graphics library in C. It provides functions for drawing simple shapes like lines, circles, and rectangles. It also includes functions for setting colors and changing the background. The graphics.h library is a part of the Turbo C compiler and is not available in other compilers.
 

2. SDL (Simple DirectMedia Layer): SDL is a cross-platform library that provides a set of functions for creating games and multimedia applications. It includes functions for drawing 2D graphics, handling input devices, and playing sound. SDL is available for many platforms, including Windows, Mac, and Linux.
 

3. OpenGL (Open Graphics Library): OpenGL is a powerful graphics library that provides functions for creating 3D graphics. It is widely used in video games, scientific visualization, and computer-aided design. OpenGL is available on many platforms and is supported by most modern graphics cards.
 

4. Cairo: Cairo is a 2D graphics library that provides functions for drawing high-quality vector graphics. It supports many output formats, including PNG, PDF, and SVG. Cairo is available on many platforms and is used in many open-source projects.
 

Note: To use these libraries in your C program, you need to include the appropriate header file and link your program with the library file. For example, to use the graphics.h library, you need to include the graphics.h header file and link your program with the graphics.lib library file.

Colors of Graphics Program in C

In graphics programming, colors are an essential element for creating visually appealing and interactive programs. C graphics libraries provide functions for setting and manipulating colors. The most common way to represent colors in C is by using the RGB (Red, Green, Blue) color model.

In the RGB color model, each color is represented by a combination of red, green, and blue values. Each value ranges from 0 to 255, where 0 means no intensity and 255 means full intensity. For example, the color red is represented by the values (255, 0, 0), green by (0, 255, 0), and blue by (0, 0, 255).

Here are some common colors and their RGB values:

- Black: (0, 0, 0)
 

- White: (255, 255, 255)
 

- Red: (255, 0, 0)
 

- Green: (0, 255, 0)
 

- Blue: (0, 0, 255)
 

- Yellow: (255, 255, 0)
 

- Magenta: (255, 0, 255)
 

- Cyan: (0, 255, 255)


In C graphics programming, you can set the color of graphical elements using functions provided by the graphics library. For example, in the graphics.h library, you can use the setcolor() function to set the current drawing color, like this:

setcolor(RED);


This sets the current drawing color to red, and any graphical elements drawn after this statement will be in red.


You can also create your own colors by specifying the RGB values. For example, to create a purple color, you can use:

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


This creates a purple color by mixing red and blue values.

Syntax of Graphics Program in C

Let’s see the basic syntax below :

#include <graphics.h>

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

    // Your graphics code goes here

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


Let’s discuss the components of syntax : 


1. `#include <graphics.h>`: This line includes the graphics.h header file, which contains the functions and constants needed for graphics programming.
 

2. `int main() { ... }`: This is the main function where your program starts executing.
 

3. `int gd = DETECT, gm;`: These lines declare two integer variables, `gd` and `gm`. `gd` is set to `DETECT`, which automatically detects the graphics driver. `gm` is used to store the graphics mode.
 

4. `initgraph(&gd, &gm, "");`: This function initializes the graphics system. It takes three arguments: the address of `gd`, the address of `gm`, and a string specifying the path to the graphics driver (usually left empty).
 

5. `// Your graphics code goes here`: This is where you write your graphics code, such as drawing shapes, setting colors, and creating animations.
 

6. `getch();`: This function waits for a key press from the user before closing the graphics window.
 

7. `closegraph();`: This function closes the graphics system and frees up any allocated memory.
 

8. `return 0;`: This line ends the main function and returns 0 to indicate successful program execution.


Let’s see an example of a simple graphics program that draws a red circle:

  • C

C

#include <graphics.h>

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

setcolor(RED);
circle(100, 100, 50);

getch();
closegraph();
return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output

Output

This program initializes the graphics system, sets the drawing color to red, draws a circle at coordinates (100, 100) with a radius of 50 pixels, waits for a key press, and then closes the graphics system.

Applications of Graphics Program in C:

1. Game Development:Graphics programming is extensively used in game development to create visually appealing and interactive games. C graphics libraries like SDL and OpenGL are commonly used to render game graphics, animate characters, and create special effects. Graphics programming allows game developers to create immersive 2D and 3D game worlds.
 

2. Computer-Aided Design (CAD):Graphics programming is used in CAD software to create and manipulate 2D and 3D models of objects. CAD applications rely on graphics libraries to render complex geometries, apply textures, and simulate lighting and shading effects. Graphics programming enables engineers and designers to visualize and analyze their designs before manufacturing.
 

3. Data Visualization:Graphics programming is used to create visual representations of data, such as charts, graphs, and diagrams. C graphics libraries provide functions for drawing lines, curves, and shapes, making it possible to create informative and visually appealing data visualizations. This is particularly useful in scientific and business applications where large amounts of data need to be presented in a meaningful way.
 

4. Image Processing:Graphics programming in C is used for image processing tasks, such as image filtering, enhancement, and manipulation. C graphics libraries provide functions for loading, saving, and modifying image files. Image processing algorithms can be implemented using graphics programming to perform operations like resizing, cropping, and applying special effects to images.
 

5. Graphical User Interfaces (GUIs):Graphics programming is used to create graphical user interfaces for software applications. C graphics libraries like GTK and Qt provide tools and widgets for building interactive and user-friendly interfaces. Graphics programming allows developers to create windows, buttons, menus, and other GUI elements that facilitate user interaction with the application.
 

6. Simulations and Visualizations:Graphics programming is used in simulations and visualizations to create realistic and interactive representations of real-world systems. For example, graphics programming can be used to simulate physical phenomena, visualize scientific data, or create virtual environments for training and education purposes. Graphics programming enables the creation of dynamic and interactive simulations that enhance understanding and decision-making.
 

7. Embedded Systems:Graphics programming is used in embedded systems to create graphical displays and user interfaces. Embedded devices like smart appliances, medical equipment, and automotive systems often require graphical displays to present information and interact with users. C graphics libraries optimized for embedded systems, such as Embedded Graphics Library (EGL), are used to create efficient and responsive graphical interfaces.

Write a Program to Draw Animation Using Increasing Circles Filled with Different Colors and Patterns

This program creates an animation of circles that gradually increase in size while being filled with different colors and patterns. We use the graphics.h library to achieve this effect.

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

void drawIncreasingCircles() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\Turboc3\\BGI");  // Initialize graphics mode

    int x = getmaxx() / 2, y = getmaxy() / 2; // Center of the screen
    int radius = 10;
    
    for (int i = 0; i < 10; i++) {
        setfillstyle(i % 11, i + 1);  // Change fill style and color
        setcolor(i + 1);  // Change outline color
        fillellipse(x, y, radius, radius);
        delay(500);  // Pause for animation effect
        radius += 20;  // Increase radius
    }

    getch();
    closegraph();
}

int main() {
    drawIncreasingCircles();
    return 0;
}

 

Explanation:

  1. Initializes the graphics mode.
  2. Defines the center of the screen where circles will be drawn.
  3. Uses a loop to create circles with increasing radii.
  4. Fills each circle with different colors and patterns.
  5. Introduces a delay to create an animation effect.

Program to Make a Screen Saver Displaying Different Size Circles Filled with Different Colors at Random Places

This program randomly generates circles of different sizes and colors at random positions on the screen, mimicking a screensaver effect.

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

void screenSaver() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

    srand(time(0));  // Seed for randomness

    for (int i = 0; i < 50; i++) {
        int x = rand() % getmaxx();  // Random x-coordinate
        int y = rand() % getmaxy();  // Random y-coordinate
        int radius = rand() % 50 + 10;  // Random radius (10 to 60)
        int color = rand() % 15 + 1;  // Random color (1 to 15)
        
        setfillstyle(SOLID_FILL, color);
        setcolor(color);
        fillellipse(x, y, radius, radius);
        delay(200);
    }

    getch();
    closegraph();
}

int main() {
    screenSaver();
    return 0;
}

 

Explanation:

  1. Initializes graphics mode.
  2. Uses rand() to generate random positions, colors, and radii for circles.
  3. Draws 50 circles at different locations with varied sizes.
  4. Introduces a delay for animation effects.

Write a Program to Make a Moving Colored Car Using Inbuilt Functions

This program creates a simple car and moves it across the screen using a loop.

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

void drawCar(int x) {
    setcolor(WHITE);
    rectangle(x, 300, x + 100, 350); // Car body
    rectangle(x + 20, 270, x + 80, 300); // Car top
    setfillstyle(SOLID_FILL, RED);
    floodfill(x + 21, 271, WHITE);
    
    setcolor(YELLOW);
    circle(x + 20, 360, 10);  // Front wheel
    circle(x + 80, 360, 10);  // Rear wheel
    setfillstyle(SOLID_FILL, BLUE);
    floodfill(x + 21, 361, YELLOW);
    floodfill(x + 81, 361, YELLOW);
}

void moveCar() {
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

    for (int i = 0; i < getmaxx(); i += 5) {
        cleardevice();
        drawCar(i);
        delay(50);
    }

    getch();
    closegraph();
}

int main() {
    moveCar();
    return 0;
}

 

Explanation:

  1. Defines drawCar() to draw a car using rectangle() and circle().
  2. Uses moveCar() to animate the car by incrementing its position in a loop.
  3. Clears the screen (cleardevice()) and redraws the car at a new position in each iteration.
  4. Uses delay(50) to control the speed of movement.

Write a Program to Print Your Name in Hindi Script on Console Output in C

To print Hindi script on the console, we use Unicode characters and set the console to support Hindi fonts.

#include <stdio.h>
#include <locale.h>
#include <wchar.h>

int main() {
    setlocale(LC_ALL, ""); // Enable Unicode support
    wprintf(L"मेरा नाम नारायण मिश्रा है।\n");
    return 0;
}

 

Explanation:

  1. setlocale(LC_ALL, ""); enables Unicode support for Hindi characters.
  2. wprintf(L"...") prints Hindi text using a wide-character string (L prefix).
  3. The output displays "मेरा नाम है।" in Hindi script.

Advantages of Graphics Program in C:

1. High Performance: C is known for its high performance and efficiency. When it comes to graphics programming, performance is crucial, especially for real-time applications like games and simulations. C allows low-level access to system resources, enabling developers to optimize their code for maximum performance. C graphics libraries are often well-optimized and provide efficient rendering capabilities.
 

2. Low-level Control: C provides low-level control over system resources, including memory management and hardware access. This level of control is particularly useful in graphics programming, where developers need to interact directly with the graphics hardware to achieve optimal performance. C allows developers to fine-tune their code and make the most efficient use of system resources.
 

3. Portability: C is a highly portable language, meaning that C programs can be easily compiled and run on different platforms and operating systems. This portability extends to graphics programming as well. Many C graphics libraries, such as SDL and OpenGL, are cross-platform and can be used on various operating systems, including Windows, macOS, and Linux. This portability allows developers to create graphics applications that can reach a wide audience.
 

4. Extensive Libraries and Tools: C has a rich ecosystem of libraries and tools that support graphics programming. Graphics libraries like OpenGL and SDL provide powerful functions and abstractions for creating 2D and 3D graphics. These libraries offer a wide range of features, including rendering, texture mapping, lighting, and animation. Additionally, there are numerous tools and frameworks available for C graphics programming, such as game engines and image processing libraries, which can speed up development and provide additional functionality.
 

5. Integration with Other Languages: C can be easily integrated with other programming languages, allowing developers to leverage the strengths of multiple languages in their graphics applications. For example, C graphics libraries can be used in conjunction with higher-level languages like Python or Lua, enabling developers to combine the performance of C with the ease of use and rapid development capabilities of these languages.
 

6. Large Community and Resources: C has a large and active community of developers, which means there is a wealth of resources, tutorials, and forums available for graphics programming in C. This community support makes it easier for developers to find answers to their questions, learn best practices, and get help with troubleshooting. The abundance of resources and code samples available for C graphics programming can greatly accelerate the learning process and development workflow.
 

7. Flexibility and Customization: C provides a high degree of flexibility and customization when it comes to graphics programming. Developers have fine-grained control over the rendering pipeline, allowing them to implement custom algorithms and optimize performance for specific hardware. C graphics libraries often provide low-level APIs that give developers the freedom to implement their own rendering techniques and visual effects.

Disadvantages of Graphics Program in C:

1. Steep Learning Curve: C is a low-level language that requires a good understanding of memory management, pointers, and hardware-level concepts. Graphics programming in C adds an additional layer of complexity, as developers need to be familiar with graphics libraries, rendering pipelines, and mathematical concepts related to computer graphics. This steep learning curve can be challenging for beginners and may require a significant investment of time and effort to become proficient.
 

2. Verbose and Error-Prone: C is known for its verbosity and manual memory management, which can make the code more error-prone compared to higher-level languages. Graphics programming in C often involves working with low-level APIs, which require careful handling of memory, pointers, and data structures. This verbosity and the need for manual memory management can lead to subtle bugs and memory leaks if not handled properly, making the development process more challenging and time-consuming.
 

3. Limited Abstraction: C provides a low level of abstraction compared to higher-level languages. While this low-level control is an advantage in terms of performance and flexibility, it also means that developers have to handle many low-level details manually. Graphics programming in C often requires developers to write more code and deal with intricate details of the rendering pipeline, which can be time-consuming and error-prone. Higher-level languages and frameworks often provide abstractions and simplified APIs that can streamline the development process.
 

4. Platform Dependencies: Although C is a portable language, graphics programming in C can introduce platform dependencies. Different operating systems and graphics hardware may have varying capabilities and requirements, which can lead to compatibility issues and the need for platform-specific code. Developers may need to handle different graphics APIs, window systems, and input devices across platforms, adding complexity to the development process.
 

5. Limited Built-in Functionality: C is a relatively low-level language and does not provide extensive built-in functionality for graphics programming. While there are graphics libraries available, they may not offer the same level of convenience and ease of use as higher-level languages and frameworks. Developers often need to write more code and handle low-level details manually, which can increase development time and effort.
 

6. Debugging Challenges: Debugging graphics programs in C can be more challenging compared to higher-level languages. Graphics programming often involves complex interactions between the CPU, GPU, and other hardware components, making it harder to identify and resolve issues. Debugging low-level graphics code, especially when dealing with performance optimizations and hardware-specific bugs, can be time-consuming and require specialized tools and expertise.
 

7. Rapid Development Limitations: C is not typically associated with rapid application development. The low-level nature of C and the need for manual memory management can slow down the development process compared to higher-level languages and frameworks that offer more abstractions and automated memory management. For projects that require quick prototyping or have tight deadlines, using C for graphics programming may not be the most efficient choice.

Frequently Asked Questions

What is the difference between graphics.h and other graphics libraries like OpenGL and SDL?

graphics.h is a basic graphics library specific to the Turbo C compiler, while OpenGL and SDL are more advanced and cross-platform libraries that provide a wider range of features and better performance.

Can I create 3D graphics using C programming?

Yes, you can create 3D graphics using C programming with the help of libraries like OpenGL, which provide functions and tools specifically designed for 3D rendering and animation.

Is C the best language for graphics programming?

C is a popular choice for graphics programming due to its performance and low-level control, but there are other languages like C++ and Java that are also widely used. The best language depends on the specific requirements of the project.

Conclusion

In this article, we have discussed the fundamentals of graphics programming in C. We covered the basic concepts, libraries, colors, syntax, and examples of graphics programs. We also explained the different applications, its advantages and disadvantages. Graphics programming in C offers high performance, low-level control, and portability, which makes it a powerful tool for creating visually appealing and interactive applications. 

Live masterclass