Bresenham’s Line Drawing Algorithm

The Bresenham algorithm is a basic line drawing algorithm. It uses only integer calculations. At every step,we move one unit in x direction and choose among two candidate points in y direction.

/*Header file for built-in graphics functions such as plot() and initgraph()*/ 

/* Function To Implement Bresenham's algorithm */
void line_bresenham(int x1,int y1,int x2,int y2)
     int dx, dy, p, x, y;

     dx = (x2 - x1);
     dy = (y2 - y1);

     p = 2 * (dy) - (dx);

     x = x1;
     y = y1;

/*This function plots a pixel at coordinates(x,y) specified by first 2 arguments and third argument specifies the color of the pixel*/

 while(x <= x2)
    if(p < 0)
       p = p + 2 * (dy);
       p = p + 2 * (dy - dx);

/* Main Function */

int main()
    int x1, y1, x2, y2;
    int gd=DETECT, gm;
    initgraph(&gd,&gm,"c:\\tc\\bgi");/*loads the graphic driver and puts syetem into grpahics mode*/

 syntax for initgraph() is:
 void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);
 *graphdriver is an integer that specifies the graphics driver to be used.DETECT requests auto-detect for the driver.
 *graphmode is an integer that specifies the initial graphics mode.If *graphdriver equals DETECT,*graphmode is set by initgraph to the highest resolution available for the detected driver.

    printf("\t\t\tBRESENHAM'S LINE DRAWING ALGORITHM\t\t\t\n\tEnter the co-ordinates of first point :");
    scanf("%d %d",&x1,&y1);
    printf("\t\nEnter the coordinates of 2nd point:");
    scanf("%d %d",&x2,&y2);
 /*closegraph function closes the graphics mode, deallocates all memory allocated by graphics system and restores the screen to the original mode*/
 return 0; 

Bresenham Algorithm

You can run this code in Turbo C++. Dev C++ and Microsoft visual studio do not support graphics libraries.
You can download Turbo C++ using this link Turbo C++

Other articles related to Computer Graphics available on TutsHeap are:
Cohen Sutherland Line Clipping Algorithm
Boundary-Fill Algorithm
Flood-Fill Algorithm
Mid-Point Ellipse Drawing Algorithm
Mid-Point Circle Drawing Algorithm
DDA Line Drawing Algorithm

This content has been helpful to you?

Thanks for contributing!

Yes No