## Monday, June 20, 2011

### CS2405 Implementation of Bresenhams Algorithm – Line, Circle, Ellipse

Implementation of Bresenhams Algorithm – Line, Circle, Ellipse

BRESENHAM’S LINE DRAWING

AIM:
To implement Bresenham’s line drawing Algorithm for drawing lines.

FUNCTIONS USED:
Line ()

The function line () is used to draw a line from(x1, y1) to (x2, y2)
Syntax:

line (x1,y1,x2,y2)
initgraph().

This function takes thee arguments and they are
i).the video driver to be used (gd).
ii).the graphics mode (gm).
iii).the path name.
Syntax
Initgraph(gd,gm,path)

ALGORITHM:

Step 1: Start
Step 2: Get the values of the end points as(x1, y1) &(x2, y2)
Step 3: Assign x=x1, y=y1;
Step 4: Compute dx=x2-x1
Step 5: Compute dy=y2-y1
Step 6: Assign sx=x2-x1, sy=y2-y1
Step 7: If dy>dx then interchange the values of dx and dy and assign exch=1
Step 8: Compute p=2xdy-dx
Step 9: Put a pixel on(x,y)
Step 10: If exch=1, y=sy else x=x+sx
Step 11: If p>0 and exch =1, x=x+sx else y=y+sy, p=p-2xdx
Step 12: Compute p=p+2xdy
Step 13: Do steps (9) t0 (12) for dx times
Step 14: Stop

PROGRAM:

#include<iostream.h>
#include<graphics.h>
#include<conio.h>
#include<math.h>
int signs(int m);
void bres_line(int,int,int,int);
void main()
{
int gd=DETECT,gm;
int x1,x2,y1,y2;
initgraph(&gd,&gm,"");
cout<<"enter starting value of X-Axis----->";
cin>>x1;
cout<<"enter starting value of Y-Axis----->";
cin>>y1;
cout<<"enter ending value of X-Axis----->";
cin>>x2;
cout<<"enter ending value of y-Axis----->";
cin>>y2;
bres_line(x1,y1,x2,y2);
getch();
closegraph();
}
void bres_line(int x1,int y1,int x2,int y2)
{
int x,y,sx,sy,p,temp,exch=0,i,dx,dy;
x=x1;
y=y1;
dy=abs(y1-y2);
dx=abs(x1-x2);
sx=signs(x2-x1);
sy=signs(y2-y1);
if(dy>dx)
{
temp=dx;
dx=dy;
dy=temp;
exch=1;
}
p=2*dy-dx;
for(i=0;i<=dx;i++)
{putpixel(x,y,15);

if(exch==1)
y+=sy;
else
x+=sx;
if(p>=0)
{
if(exch==1)
x+=sx;
else
y+=sy;p=p-2*dx;}
p=p+2*dy;
}
}
int signs(int m)
{
if(m<0)
return(-1);
else if(m>0)
return(1);
else
return(0);
}

INPUT:

Enter starting value of X-Axis----->100
Enter starting value of Y-Axis----->100
Enter ending value of X-Axis----->200
Enter ending value of Y-Axis----->200

OUTPUT:

RESULT:
Thus the program is executed and verified.