IMPLEMENTATION OF BRESENHAM LINE DRAWING ALGORITHM USING C++

 IMPLEMENTATION OF BRESENHAM LINE DRAWING ALGORITHM USING C++

CODE:

#include<stdio.h>
#include<graphics.h>
void drawline(int,int,int,int);

int abs(int n){
    return n<0?-n:n;
}
void swap(int *a, int *b){
    *a = (*a+*b) - (*b=*a);
}
int main(){
    int x1, x2, y1, y2;
    printf("Enter the first point ");
    scanf("%d%d",&x1,&y1);
    printf("Enter the second point ");
    scanf("%d%d",&x2,&y2);
    int gd=DETECT, gm;
    initgraph(&gd,&gm,NULL);
    drawline(x1,y1,x2,y2);
    getch();
    closegraph();
}

void drawline(int x1, int y1, int x2, int y2)
{
    int dx, dy, p, xs, ys, xe, ye, x, y;
    dx=x2-x1;
    dy=y2-y1;
    p=2*dy-dx;

    if(abs(dx)>=abs(dy)){
        if(dx>=0){
            x = xs = x1, y = ys = y1, xe = x2, ye = y2;
        }
        else if(dx<0){
            x = xs = x2, y = ys = y2, xe = x1, ye = y1;
        }
        dx = xe-xs, dy = ye-ys;
        int step = dy!=0? dy/abs(dy) : 0;
        dx = abs(dx), dy = abs(dy);
        p = 2*dy-dx;
        while (x <= xe)
        {
            putpixel(x,y,WHITE);
            x = x + 1;
            y = p>0 ? y+step : y;
            p = p>0 ? p+2*dy-2*dx : p+2*dy;
        }
    }
    else{
        if(dy>=0){
            x = xs = x1, y = ys = y1, xe = x2, ye = y2;
        }
        else if(dy<0){
            x = xs = x2, y = ys = y2, xe = x1, ye = y1;
        }
        dx = xe-xs, dy = ye-ys;
        int step = dx!=0? dx/abs(dx) : 0;
        dx = abs(dx), dy = abs(dy);
        p = 2*dx-dy;
        while (y <= ye)
        {
            putpixel(x,y,WHITE);
            y = y + 1;
            x = p>0 ? x+step : x;
            p = p>0 ? p+2*dx-2*dy : p+2*dx;
        }
    }
}

INPUT:

enter the first point 50 50
enter the second point 300 300

OUTPUT:


Comments

Popular posts from this blog

C++ PROGRAM TO IMPLEMENT THE CONCEPT OF 8 WAY BOUNDARY FILLING ALGORITHM

C++ PROGRAM TO IMPLEMENT THE CONCEPT OF REFLEXION

C++ PROGRAM TO IMPLEMENT THE CONCEPT OF FIXED SCALING