Graphics Programming with graphics.h
Learn C graphics programming! Draw circles, ellipses, rectangles, and more using graphics.h. Covers OS/compiler support, setup instructions, and modern alternatives.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Understand what graphics.h is and its history
- ✓Know which OS and compilers support graphics.h
- ✓Set up graphics.h with MinGW or Dev-C++
- ✓Draw circles, ellipses, rectangles, and lines
- ✓Use colors, fill patterns, and line styles
- ✓Create polygons and complex shapes
- ✓Know modern alternatives like SDL2 and OpenGL
?Why Learn Graphics Programming?
Graphics programming helps you visualize data, create games, and understand how computers display images.
Visualization
Charts, graphs, plots
Games
Simple 2D games
Understanding
How displays work
Modern alternatives: While graphics.h is great for learning, modern projects use SDL2, OpenGL,Raylib, or SFML. We cover graphics.h here because many schools still teach it.
Graphics programming in C allows you to create visual applications — from simple shapes to complex animations. The graphics.h header file provides functions for drawing lines, circles, rectangles, and more. This tutorial covers everything you need to get started with graphics programming in C.
What is graphics.h?
graphics.h is a header file that contains declarations for graphics functions and constants. It was originally developed by Borland for their Turbo C/C++ compiler in the 1980s-90s.
- •Provides simple 2D graphics functions for drawing shapes
- •Uses BGI (Borland Graphics Interface) for rendering
- •Great for learning graphics fundamentals and basic visualization
Operating System & Compiler Support
Important: Platform Limitations
The original graphics.h was designed for DOS-based systems and is not natively supported on modern operating systems. However, there are ways to use it on different platforms.
| Operating System | Compiler | Support Level | Notes |
|---|---|---|---|
| Windows 10/11 | MinGW GCC + WinBGIm | Works Well | Requires WinBGIm library installation |
| Windows | Turbo C/C++ (DOSBox) | Native Support | Run Turbo C in DOSBox emulator |
| Windows | Dev-C++ (with graphics) | Works Well | Use Orwell Dev-C++ with graphics DevPak |
| Linux | GCC + libgraph | Partial Support | Requires libgraph library compilation |
| macOS | GCC / Clang | Not Supported | Use SDL2 or OpenGL instead |
| DOS (DOSBox) | Turbo C/C++ 3.0 | Full Support | Original intended environment |
Detailed Compiler Support
Turbo C/C++ (Native)
- • Versions: Turbo C 2.0, Turbo C++ 3.0
- • OS: MS-DOS, Windows (via DOSBox)
- • graphics.h: Built-in, no setup required
- • BGI Drivers: Included in /BGI folder
MinGW GCC + WinBGIm
- • Versions: GCC 8.0+, MinGW-w64
- • OS: Windows 7/10/11
- • Library: WinBGIm (Windows BGI)
- • Compilation: -lbgi -lgdi32 -lcomdlg32
Code::Blocks
- • Versions: 17.12+
- • OS: Windows
- • Setup: Add WinBGIm to linker settings
- • Libraries: -lbgi -lgdi32 -luser32
Dev-C++
- • Versions: Orwell Dev-C++ 5.11+
- • OS: Windows
- • Setup: Install Graphics DevPak
- • Easiest: Recommended for beginners
Setup Instructions
Method 1: Windows with MinGW (Recommended)
Install MinGW-w64
Download from https://www.mingw-w64.org/ and install to C:\mingw64
Download WinBGIm Library
Get graphics.h, winbgim.h, and libbgi.a from WinBGIm project
Copy Files to MinGW
1# Copy header files to include folder2copy graphics.h C:\mingw64\include\3copy winbgim.h C:\mingw64\include\45# Copy library file to lib folder6copy libbgi.a C:\mingw64\lib\Compile Your Program
1# Compile with required linker flags2g++ -o myprogram.exe myprogram.cpp -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32Method 2: Dev-C++ (Easiest for Beginners)
Download Orwell Dev-C++
Get from https://sourceforge.net/projects/orwelldevcpp/
Download Graphics DevPak
Search for "Graphics.h DevPak for Dev-C++" and download the .DevPak file
Install the DevPak
Double-click the .DevPak file to install graphics support automatically
Configure Project
Go to Project → Project Options → Parameters → Add: -lbgi -lgdi32 -lcomdlg32 -luuid -loleaut32 -lole32
Method 3: Linux with libgraph
1# Install dependencies (Ubuntu/Debian)2sudo apt-get install build-essential3sudo apt-get install libsdl-image1.2 libsdl-image1.2-dev guile-2.04sudo apt-get install guile-2.0-dev libsdl1.2debian libart-2.0-dev56# Download and compile libgraph7git clone https://github.com/SagarGaniga/Graphics-Library.git8cd Graphics-Library9./configure10make11sudo make install12sudo ldconfig1314# Compile your program15gcc myprogram.c -o myprogram -lgraphNote: libgraph may have limited functionality compared to the original graphics.h. For serious graphics work on Linux, consider SDL2 or OpenGL.
Key Graphics Functions
| Function | Purpose | Syntax |
|---|---|---|
| initgraph() | Initialize graphics mode | initgraph(&gd, &gm, "path") |
| closegraph() | Close graphics mode | closegraph() |
| circle() | Draw a circle | circle(x, y, radius) |
| ellipse() | Draw an ellipse | ellipse(x, y, start, end, xr, yr) |
| line() | Draw a line | line(x1, y1, x2, y2) |
| rectangle() | Draw a rectangle | rectangle(x1, y1, x2, y2) |
| arc() | Draw an arc | arc(x, y, start, end, radius) |
| setcolor() | Set drawing color | setcolor(color) |
| setfillstyle() | Set fill pattern & color | setfillstyle(pattern, color) |
| floodfill() | Fill enclosed area | floodfill(x, y, border) |
| outtextxy() | Display text at position | outtextxy(x, y, "text") |
| getmaxx() | Get max X coordinate | int x = getmaxx() |
| getmaxy() | Get max Y coordinate | int y = getmaxy() |
Available Colors
0
BLACK
#000000
1
BLUE
#0000AA
2
GREEN
#00AA00
3
CYAN
#00AAAA
4
RED
#AA0000
5
MAGENTA
#AA00AA
6
BROWN
#AA5500
7
LIGHTGRAY
#AAAAAA
8
DARKGRAY
#555555
9
LIGHTBLUE
#5555FF
10
LIGHTGREEN
#55FF55
11
LIGHTCYAN
#55FFFF
12
LIGHTRED
#FF5555
13
LIGHTMAGENTA
#FF55FF
14
YELLOW
#FFFF55
15
WHITE
#FFFFFF
Fill Patterns (setfillstyle)
Background color only
Solid fill color
Horizontal lines ───
Light slashes ///
Dense slashes ///
Backslashes \\\
Light backslashes
Cross hatch +++
Diagonal cross XXX
Interleaved lines
Wide spaced dots
Close spaced dots
Understanding Screen Coordinates
Graphics Coordinate System
Unlike math class, screen coordinates have (0,0) at the top-left corner
Left to right
Top to bottom
Example 1: Drawing a Circle
The circle() function draws a circle at a specified center point with a given radius. The syntax is circle(x, y, radius).
1#include <graphics.h>2#include <conio.h>34int main() {5 int gd = DETECT, gm; // Graphics driver and mode6 7 // Initialize graphics mode8 // DETECT: Auto-detect the best graphics driver9 // "" or "C:\\TC\\BGI": Path to BGI files (use "" for WinBGIm)10 initgraph(&gd, &gm, "");11 12 // Get the center of the screen13 int centerX = getmaxx() / 2; // Half of screen width14 int centerY = getmaxy() / 2; // Half of screen height15 16 // Draw a title17 setcolor(YELLOW);18 outtextxy(centerX - 80, 30, "Circle Example in C");19 20 // Draw a simple circle at center with radius 10021 setcolor(WHITE);22 circle(centerX, centerY, 100);23 24 // Draw more circles with different radii25 setcolor(LIGHTCYAN);26 circle(centerX, centerY, 50); // Smaller inner circle27 28 setcolor(LIGHTGREEN);29 circle(centerX, centerY, 150); // Larger outer circle30 31 // Draw filled circle32 setcolor(LIGHTRED);33 setfillstyle(SOLID_FILL, LIGHTRED);34 circle(centerX - 200, centerY, 40);35 floodfill(centerX - 200, centerY, LIGHTRED);36 37 // Wait for keypress38 getch();39 40 // Close graphics mode41 closegraph();42 43 return 0;44}Expected Output:
Circle Example in C
Filled Circle
Press any key to exit...
Step-by-Step Explanation:
- Initialize Graphics:
initgraph(&gd, &gm, "")sets up the graphics system. DETECT auto-selects the driver. - Find Screen Center:
getmaxx()/2andgetmaxy()/2give us the center coordinates. - Draw Circle:
circle(centerX, centerY, 100)draws a circle with radius 100 pixels. - Filled Circle: Use
floodfill()after setting fill style to create filled shapes. - Cleanup:
closegraph()releases graphics memory.
Example 2: Drawing an Ellipse
An ellipse is like a stretched circle. The ellipse() function has more parameters to control the horizontal and vertical radii, plus start and end angles for partial ellipses.
Syntax: ellipse(x, y, start_angle, end_angle, x_radius, y_radius)
- • x, y: Center coordinates
- • start_angle, end_angle: 0 to 360 for full ellipse
- • x_radius: Horizontal radius
- • y_radius: Vertical radius
1#include <graphics.h>2#include <conio.h>34int main() {5 int gd = DETECT, gm;6 7 // Initialize graphics8 initgraph(&gd, &gm, "");9 10 // Get screen dimensions11 int maxX = getmaxx();12 int maxY = getmaxy();13 int centerX = maxX / 2;14 int centerY = maxY / 2;15 16 // Title17 setcolor(YELLOW);18 outtextxy(centerX - 100, 20, "Ellipse Examples in C");19 20 // Example 1: Full ellipse (horizontal - wider than tall)21 setcolor(LIGHTGREEN);22 ellipse(centerX, centerY - 100, 0, 360, 150, 60);23 outtextxy(centerX - 60, centerY - 100 - 80, "Horizontal Ellipse");24 25 // Example 2: Full ellipse (vertical - taller than wide)26 setcolor(LIGHTCYAN);27 ellipse(centerX, centerY + 100, 0, 360, 60, 120);28 outtextxy(centerX - 50, centerY + 100 + 130, "Vertical Ellipse");29 30 // Example 3: Half ellipse (top half - 0 to 180 degrees)31 setcolor(LIGHTRED);32 ellipse(100, centerY, 0, 180, 80, 50);33 outtextxy(50, centerY - 80, "Top Half");34 35 // Example 4: Quarter ellipse (0 to 90 degrees)36 setcolor(LIGHTMAGENTA);37 ellipse(maxX - 100, centerY, 0, 90, 80, 50);38 outtextxy(maxX - 150, centerY - 80, "Quarter");39 40 // Example 5: Filled ellipse41 setcolor(YELLOW);42 setfillstyle(SOLID_FILL, YELLOW);43 ellipse(centerX, centerY, 0, 360, 40, 25);44 // For filled ellipse, use fillellipse() if available45 // Otherwise use floodfill46 floodfill(centerX, centerY, YELLOW);47 outtextxy(centerX - 30, centerY + 35, "Filled");48 49 getch();50 closegraph();51 52 return 0;53}Expected Output:
Ellipse Examples in C
Horizontal Ellipse
Top Half
Filled
Quarter
Vertical Ellipse
Understanding Ellipse Parameters:
| Type | Start Angle | End Angle | Result |
|---|---|---|---|
| Full Ellipse | 0 | 360 | Complete ellipse |
| Top Half | 0 | 180 | Upper semicircle |
| Bottom Half | 180 | 360 | Lower semicircle |
| Quarter | 0 | 90 | First quadrant |
Example 3: Rectangles and Bars
The rectangle() function draws an outline, whilebar() draws a filled rectangle. These are essential for UI elements, charts, and game graphics.
1#include <graphics.h>2#include <conio.h>34int main() {5 int gd = DETECT, gm;6 7 initgraph(&gd, &gm, "");8 9 int maxX = getmaxx();10 int maxY = getmaxy();11 12 // Title13 setcolor(YELLOW);14 outtextxy(maxX/2 - 120, 20, "Rectangles and Bars in C");15 16 // Example 1: Simple rectangle outline17 setcolor(WHITE);18 rectangle(50, 80, 200, 180);19 outtextxy(70, 190, "rectangle()");20 21 // Example 2: Filled bar (solid rectangle)22 setcolor(LIGHTGREEN);23 setfillstyle(SOLID_FILL, LIGHTGREEN);24 bar(250, 80, 400, 180);25 outtextxy(300, 190, "bar()");26 27 // Example 3: 3D Bar effect28 setcolor(LIGHTCYAN);29 setfillstyle(SOLID_FILL, CYAN);30 bar3d(450, 80, 550, 180, 20, 1); // With 3D depth31 outtextxy(460, 190, "bar3d()");32 33 // Example 4: Different fill patterns34 int patterns[] = {EMPTY_FILL, SOLID_FILL, LINE_FILL, 35 LTSLASH_FILL, SLASH_FILL, BKSLASH_FILL,36 LTBKSLASH_FILL, HATCH_FILL};37 char* patternNames[] = {"EMPTY", "SOLID", "LINE", 38 "LTSLASH", "SLASH", "BKSLASH",39 "LTBKSLASH", "HATCH"};40 41 int startX = 50;42 int y = 260;43 44 outtextxy(50, 230, "Fill Patterns:");45 46 for(int i = 0; i < 8; i++) {47 setcolor(WHITE);48 setfillstyle(patterns[i], LIGHTMAGENTA);49 bar(startX + i*75, y, startX + i*75 + 60, y + 60);50 rectangle(startX + i*75, y, startX + i*75 + 60, y + 60);51 outtextxy(startX + i*75, y + 70, patternNames[i]);52 }53 54 // Example 5: Nested rectangles (frame effect)55 setcolor(RED);56 rectangle(50, 380, 200, 480);57 setcolor(YELLOW);58 rectangle(60, 390, 190, 470);59 setcolor(GREEN);60 rectangle(70, 400, 180, 460);61 setcolor(CYAN);62 rectangle(80, 410, 170, 450);63 outtextxy(70, 490, "Nested Frame");64 65 getch();66 closegraph();67 68 return 0;69}Expected Output:
| Function | Visual | Description | Use Case |
|---|---|---|---|
| rectangle() | Draws outline only | Borders, frames | |
| bar() | Filled rectangle | Buttons, bars, blocks | |
| bar3d() | 3D effect bar | Charts, 3D effects |
Nested Rectangles
Multiple rectangle() calls with different colors create a frame effect
Function Comparison:
| Function | Parameters | Description |
|---|---|---|
| rectangle() | (x1, y1, x2, y2) | Draws outline only (no fill) |
| bar() | (x1, y1, x2, y2) | Draws filled rectangle (uses fillstyle) |
| bar3d() | (x1, y1, x2, y2, depth, topflag) | Draws 3D bar with depth effect |
Example 4: Lines, Arcs, and Polygons
Beyond basic shapes, graphics.h provides functions for drawing lines, arcs, and complex polygons. These are useful for creating diagrams, charts, and custom shapes.
1#include <graphics.h>2#include <conio.h>3#include <math.h> // For sin, cos45int main() {6 int gd = DETECT, gm;7 8 initgraph(&gd, &gm, "");9 10 int maxX = getmaxx();11 int maxY = getmaxy();12 13 // Title14 setcolor(YELLOW);15 outtextxy(maxX/2 - 120, 10, "Lines, Arcs and Polygons");16 17 // ========== LINES ==========18 outtextxy(50, 50, "Lines:");19 20 // Simple line21 setcolor(WHITE);22 line(50, 80, 200, 80);23 outtextxy(210, 75, "line()");24 25 // Different line styles26 int styles[] = {SOLID_LINE, DOTTED_LINE, CENTER_LINE, DASHED_LINE};27 char* styleNames[] = {"SOLID", "DOTTED", "CENTER", "DASHED"};28 29 for(int i = 0; i < 4; i++) {30 setlinestyle(styles[i], 0, NORM_WIDTH);31 setcolor(LIGHTCYAN);32 line(50, 110 + i*25, 180, 110 + i*25);33 outtextxy(190, 105 + i*25, styleNames[i]);34 }35 36 // ========== ARCS ==========37 setlinestyle(SOLID_LINE, 0, NORM_WIDTH);38 outtextxy(320, 50, "Arcs:");39 40 // Full arc (like a rainbow)41 setcolor(LIGHTRED);42 arc(400, 150, 0, 180, 80); // Upper half43 44 setcolor(LIGHTGREEN);45 arc(400, 150, 30, 150, 60); // Smaller arc46 47 setcolor(LIGHTMAGENTA);48 arc(400, 150, 60, 120, 40); // Even smaller49 50 outtextxy(360, 160, "arc() - Rainbow");51 52 // ========== POLYGON ==========53 outtextxy(50, 250, "Polygons:");54 55 // Triangle using drawpoly56 int triangle[] = {100, 290, 150, 350, 50, 350, 100, 290};57 setcolor(LIGHTCYAN);58 drawpoly(4, triangle); // 4 points (last = first to close)59 outtextxy(70, 360, "Triangle");60 61 // Pentagon (5 sides)62 int pentagon[12]; // 6 points * 2 coordinates63 int cx = 250, cy = 320, radius = 40;64 for(int i = 0; i < 6; i++) {65 pentagon[i*2] = cx + radius * cos(2*3.14159*i/5 - 3.14159/2);66 pentagon[i*2+1] = cy + radius * sin(2*3.14159*i/5 - 3.14159/2);67 }68 setcolor(LIGHTGREEN);69 drawpoly(6, pentagon);70 outtextxy(220, 370, "Pentagon");71 72 // Star (filled polygon)73 int star[22]; // 11 points74 cx = 380; cy = 320;75 for(int i = 0; i < 10; i++) {76 int r = (i % 2 == 0) ? 50 : 20; // Alternate radius77 star[i*2] = cx + r * cos(2*3.14159*i/10 - 3.14159/2);78 star[i*2+1] = cy + r * sin(2*3.14159*i/10 - 3.14159/2);79 }80 star[20] = star[0]; // Close the star81 star[21] = star[1];82 83 setcolor(YELLOW);84 setfillstyle(SOLID_FILL, YELLOW);85 fillpoly(11, star);86 outtextxy(360, 380, "Star");87 88 // ========== BEZIER/SPLINE EFFECT ==========89 outtextxy(480, 250, "Curved Lines:");90 91 // Create smooth curve using multiple small lines92 setcolor(LIGHTMAGENTA);93 int prevX = 500, prevY = 320;94 for(int x = 0; x <= 100; x += 2) {95 int y = 320 + 30 * sin(x * 3.14159 / 25);96 line(prevX, prevY, 500 + x, y);97 prevX = 500 + x;98 prevY = y;99 }100 outtextxy(510, 380, "Sine Wave");101 102 getch();103 closegraph();104 105 return 0;106}Expected Output:
Lines, Arcs and Polygons
Lines:
Arcs (Rainbow):
Polygons:
Triangle
Pentagon
Star
Sine Wave
Line Styles Reference:
setlinestyle(style, pattern, thickness)
- •
SOLID_LINE (0)- Continuous line - •
DOTTED_LINE (1)- Dotted pattern - •
CENTER_LINE (2)- Center line (─·─·─) - •
DASHED_LINE (3)- Dashed pattern
Thickness Options
- •
NORM_WIDTH (1)- Normal width (1 pixel) - •
THICK_WIDTH (3)- Thick width (3 pixels)
Modern Alternatives to graphics.h
While graphics.h is great for learning, modern graphics programming uses more powerful and cross-platform libraries. Here are the recommended alternatives:
SDL2 (Simple DirectMedia Layer)
Cross-platform, modern, widely used for games
- ✓Works on Windows, Linux, macOS
- ✓2D and 3D graphics support
- ✓Audio, input, networking
- ✓Active development and community
OpenGL
Industry standard for 3D graphics
- ✓Hardware-accelerated rendering
- ✓Professional quality graphics
- ✓Cross-platform (with GLFW/GLUT)
- ✓Used in games, simulations, CAD
Cairo Graphics
2D vector graphics library
- ✓High-quality anti-aliased output
- ✓PDF, SVG, PNG output
- ✓Great for GUI applications
- ✓Used in GTK+, Firefox
raylib
Simple game programming library
- ✓Easy to learn (like graphics.h)
- ✓Modern and well-maintained
- ✓2D and 3D support
- ✓Great documentation
Best Practices
Always call closegraph()
Release graphics memory before program exits to prevent memory leaks
Check for initialization errors
Use graphresult() after initgraph() to check if graphics initialized successfully
Use getmaxx() and getmaxy() for positioning
Makes your graphics code resolution-independent
Don't use graphics.h for production software
It's meant for learning. Use SDL2, OpenGL, or raylib for real applications
!Code Pitfalls: Common Mistakes & What to Watch For
Copied code often suggests `graphics.h` for graphics programming without warning about its severe limitations and obsolescence.
If you search online to "draw a circle in C," it will likely provide `graphics.h` code with `initgraph()` and `circle()`. While syntactically correct, this code won't compile on modern compilers without significant setup (WinBGIm, DOSBox). The Code rarely explains that `graphics.h` is a DOS-era library from the 1980s that is not cross-platform, not hardware-accelerated, and not suitable for any real-world application.
The Trap: Online sources are trained on educational resources, many of which still teach `graphics.h` for simplicity. They might not mention modern alternatives like SDL2, Raylib, OpenGL, or platform-specific APIs (Win32 GDI, Xlib). Over-reliance on copying code for graphics programming can lead to frustration when your code doesn't compile, or you realize you've learned an obsolete technology.
The Reality: `graphics.h` is useful *only* for learning basic concepts or for assignments in courses that specifically require it. For any serious project—games, visualizations, or applications—you need a modern graphics library. Use resources to understand concepts, but always ask about modern alternatives and cross-platform compatibility.
Frequently Asked Questions
Q:Why doesn't graphics.h work on my modern compiler?
A: graphics.h is a legacy library from Turbo C (1980s DOS). For modern Windows, use WinBGIm with Code::Blocks or Dev-C++. For cross-platform graphics, consider SDL2 or raylib instead.
Q:What's the difference between bar() and rectangle()?
A: rectangle() draws only the outline (border) of a rectangle. bar() draws a filled rectangle using the current fill style. Use rectangle for borders, bar for filled shapes.
Q:How do I fill a circle with color?
A: Draw the circle first, then use floodfill(x, y, borderColor) with a point inside the circle. Set the fill style first withsetfillstyle(SOLID_FILL, color).
Q:Should I use graphics.h for a real project?
A: No — it's meant for learning only. For real applications, use SDL2 (games), OpenGL (3D), Cairo (2D vector), or raylib (simple games). These are cross-platform, modern, and actively maintained.
Summary
What You Learned:
- ✓What graphics.h is and its history
- ✓OS and compiler support (Windows, Linux, DOS)
- ✓How to set up graphics.h with MinGW/Dev-C++
- ✓Drawing circles, ellipses, rectangles, lines
- ✓Using colors, fill patterns, and line styles
Key Functions:
initgraph()- Start graphicsclosegraph()- End graphicscircle(x, y, r)- Draw circleellipse(x, y, sa, ea, xr, yr)- Draw ellipserectangle(x1, y1, x2, y2)- Draw rectangleline(x1, y1, x2, y2)- Draw linesetcolor(c)- Set drawing color
Test Your Knowledge
Related Tutorials
Command Line Arguments in C
Learn to pass data to your programs when running them! Master argc and argv, parse command line flags, and build powerful CLI tools.
Runtime Errors and Exceptions in C
Understand runtime errors in C: Division by zero, Segmentation faults, Memory leaks, Buffer overflows. Learn prevention and error handling techniques.
Multi-File Programs in C
Organize large projects into multiple files! Learn about header files, source files, the extern keyword, and how to compile multi-file programs.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!