← Back to C Course | Chapter 13: Graphics | Lesson 2 of 10

C graphics.h Library

The graphics.h Header

The graphics.h header file acts as a gatekeeper to access over 70 unique drawing and utility functions. It maps your program coordinates directly to the video controller memory using BGI drivers.

Example: The graphics.h Header

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	circle(100, 100, 50);
	getch();
	closegraph();
	return 0;
}

initgraph and closegraph

The initgraph() function loads the graphics driver and puts the system into graphics mode. The closegraph() function shuts down the graphics system, freeing all allocated memory and loading back the text interface.

Example: initgraph and closegraph

c
#include <graphics.h>
int main() {
	int gd = DETECT, gm;
	initgraph(&gd, &gm, "");
	getch();
	closegraph();
	return 0;
}

getmaxx and getmaxy

Screen sizes vary between platforms. Instead of hardcoding positions, use getmaxx() and getmaxy() to find the maximum resolution dynamically. This keeps your designs responsive.

Example: getmaxx and getmaxy

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	int centerX = getmaxx() / 2;
	int centerY = getmaxy() / 2;
	putpixel(centerX, centerY, WHITE);
	getch();
	closegraph();
	return 0;
}

cleardevice and Background Options

The cleardevice() function erases the current graphics screen, filling it with the background color. You can set the default background color using the setbkcolor() function.

Example: cleardevice and Background Options

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	setbkcolor(BLUE);
	cleardevice();
	getch();
	closegraph();
	return 0;
}

Modern Compatibility Details

Standard C compiler packages (like GCC on Windows or Linux) don't include graphics.h out of the box. Modern setups use custom BGI wrapper libraries, which use the same standard function signatures.

Example: Modern Compatibility Details

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	getch();
	closegraph();
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.