Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

Bresenham Line Drawing Program in C

Category: Assignment

Course: B.Tech.

Semester: 3

#include<stdio.h>
#include<dos.h>
#include<graphics.h>
#include<math.h>
#include<conio.h>

void lineBresenham(int x1, int y1, int x2, int y2) {

    int dx,dy,p,x,y,xend;

    dx = abs(x2-x1);
    dy = abs(y2-y1);
    p = 2*dy-dx;


    if(x1>x2) {
        x = x2;
        y = y2;
        xend = x1;
    }
    else {
        x = x1;
        y = y1;
        xend = x2;
    }

    putpixel(x,y,67);

    while(x < xend) {
        x++;
        if(p < 0)
            p+= 2*dy;
        else {
            y++;
            p+= 2*(dy-dx);
        }
        
        putpixel(x,y,67);

        delay(20);
    }

}

void main() {

    int x1,y1,x2,y2;

    int gd = DETECT, gm = DETECT;
    initgraph(&gd, &gm, "");

    printf("Enter the starting coordinates of line:\n");
    scanf("%d %d", &x1, &y1);
    printf("Enter the ending coordinates of line:\n");
    scanf("%d %d", &x2, &y2);

    lineBresenham(x1, y1, x2, y2);

    getch();
}

Added by inventionsbyhamid

Comments
Posted by inventionsbyhamid,

I missed the line p = 2*dy-dx; initially and unfortunately the program seemed to work fine but it's necessary to initialize p with 2*dy-dx so fix it if you are using the old version of the program.