Search This Blog

DDA Line Drawing Program in C : Computer Graphics Lab Program

Digital Differential Analyzer Algorithm or DDA algorithm is the simplest line drawing algorithm. The algorithm is taught in computer graphics subjects. The algorithm is implemented in CG labs (computer graphics labs). Borland Graphics Interface (BGI) in C is commonly used for implementing computer graphics algorithms in computer graphics labs. Here i am adding c program to draw any line with any slope using the DDA line drawing algorithm. The DDA line drawing program is as follows:

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

void dda(int x1,int y1,int x2,int y2)
{
float xincr,yincr,x,y,dx,dy,s,i;
dx=x2-x1;
dy=y2-y1;
if(abs(dx)>abs(dy))
	s=abs(dx);
else
	s=abs(dy);
xincr=dx/s;
yincr=dy/s;
x=x1;
y=y1;
for(i=0;i<s;i++)
	{
	putpixel(x,y,2);
	x+=xincr;
	y+=yincr;
	}
}

void main()
{
int gd=DETECT,gm,theta=0;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI\\");
while(!kbhit())
	{
	theta=(theta+1)%361;
	dda(300,150,300+50*sin(3.14f*theta/180),150+50*cos(3.14f*theta/180));
	delay(50);
	cleardevice();
} }


In this program, the dda line drawing algorithm is implemented as a function named dda which takes the co-ordinates of the two end points as parameters. In the main program, i have written a code which tests the DDA algorithm by drawing lines of almost all slopes.

No comments: