Search Here

C program to draw Line using Bresenham algorithm



/* C program for Bresenham Line Drawing */

#include<stdio.h>
#include<graphics.h>

int main()
{
    int gd = DETECT,gm;
    int x1,y1,x2,y2,k,dx,dy,p,x,y;
   
    printf("Enter the co-ordinates of 1st point:");
    scanf("%d %d",&x1,&y1);
    printf("Enter the co-ordinates of 2nd point:");
    scanf("%d %d",&x2,&y2);
   
    //initgraph(&gd, &gm, "C:\\TC\\BGI"); /* For Windows Turbo-C users */
    initgraph(&gd,&gm,NULL); /* For Linux users */
    setbkcolor(WHITE);

    dx=abs(x1-x2);
    dy=abs(y1-y2);
    p=2*dy-dx;
    x=x1;
    y=y1;
    
    putpixel(x1,y1,BLACK);
    for(k=1;k<=dx;k++)
    {
        if(p<0)
        {
            if(x<x2)
                x++;
            else
                x--;
            p=p+2*dy;
        }
        else
        {
            if(x<x2)
                x++;
            else
                x--;
            if(y<y2)
                y++;
            else
                y--;
            p=p+2*(dy-dx);
        }
        putpixel(x,y,BLACK);
     }
    delay(5000);
    closegraph();
    
    system("clear");
    return 0;
}


C program to draw a line using Bresenham algorithm
Output

No comments:

Post a Comment