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

C Drawing Lines & Curves

Drawing Straight Lines

line() draws a straight segment directly between two coordinates you specify explicitly — a start point (X1, Y1) and an end point (X2, Y2) — making it the simplest way to connect two known points on screen without tracking any drawing state.

Example: Drawing Straight Lines

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

Drawing from Current Position

BGI graphics maintains an implicit 'current position' cursor: moveto() repositions that cursor without drawing anything, while lineto() draws a line from wherever the cursor currently sits to a new target point and then leaves the cursor at that new point, which is convenient for drawing a connected chain of segments.

Example: Drawing from Current Position

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

Drawing Arcs

arc() draws a curved segment of a circle's circumference rather than a full circle, taking the center coordinates, a starting angle, an ending angle (both in degrees), and the radius — useful for things like pie-chart wedges or rounded corners.

Example: Drawing Arcs

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

Line Styles and Thickness

setlinestyle() changes how subsequently drawn lines look, accepting a style constant such as SOLID_LINE, DOTTED_LINE, or DASHED_LINE along with a thickness value, letting you visually distinguish different kinds of lines (like grid lines versus data lines) in the same drawing.

Example: Line Styles and Thickness

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	setlinestyle(DASHED_LINE, 0, 3);
	line(50, 50, 200, 50);
	getch();
	closegraph();
	return 0;
}

Drawing Custom Curves

Plotting individual pixels at coordinates computed from a mathematical formula inside a loop — for example using sin() and cos() to generate points along a wave — lets you draw smooth curves that none of the built-in shape functions can produce directly.

Example: Drawing Custom Curves

c
#include <graphics.h>
#include <math.h>
int main() {
	initgraph(0, 0, "");
	for (int x = 0; x < 100; x++) {
		int y = 100 + (int)(50 * sin(x * 0.1));
		putpixel(x, y, WHITE);
	}
	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.