Bresenham Line Drawing Algorithm in C
This C program draws a line between two points using Bresenham's Line Drawing Algorithm. It works
for all slopes and directions, making it suitable for student practice.
#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
void drawLine(int x1, int y1, int x2, int y2) {
int dx = abs(x2 - x1);
int dy = abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1; // step for x
int sy = (y1 < y2) ? 1 : -1; // step for y
int err = dx - dy; // error term
while (1) {
putpixel(x1, y1, WHITE); // draw pixel
if (x1 == x2 && y1 == y2) break;
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x1 += sx;
}
if (e2 < dx) {
err += dx;
y1 += sy;
}
}
}
int main() {
int gd = DETECT, gm;
int x1, y1, x2, y2;
printf("Enter x1 y1: ");
scanf("%d %d", &x1, &y1);
printf("Enter x2 y2: ");
scanf("%d %d", &x2, &y2);
initgraph(&gd, &gm, "C:\\Turboc3\\BGI"); // Update BGI path if needed
drawLine(x1, y1, x2, y2);
getch();
closegraph();
return 0;
}