C graphics.h Library
In this page:
#include <graphics.h>
int gd = DETECT, gm;
initgraph(&gd, &gm, ""); // enter graphics mode
// ... drawing calls ...
getch();
closegraph(); // leave graphics mode
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
#include <graphics.h>
int main() {
initgraph(0, 0, "");
circle(100, 100, 50);
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <graphics.h>
// Program execution starts in main()
int main() {
// Declare gd and set it to DETECT, gm
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
getch();
closegraph();
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <graphics.h>
// Program execution starts in main()
int main() {
initgraph(0, 0, "");
// Declare centerX and set it to getmaxx() / 2
int centerX = getmaxx() / 2;
// Declare centerY and set it to getmaxy() / 2
int centerY = getmaxy() / 2;
putpixel(centerX, centerY, WHITE);
getch();
closegraph();
// Return 0 to signal that the program finished successfully
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <graphics.h>
int main() {
initgraph(0, 0, "");
setbkcolor(BLUE);
cleardevice();
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <graphics.h>
int main() {
initgraph(0, 0, "");
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
- Drawing before calling
initgraph, so nothing is displayed. - Passing a wrong BGI driver path to
initgraph, so it fails to initialize graphics mode. - Forgetting
getch()beforeclosegraph(), so the window closes immediately.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: