# Draw Line using DDA Algorithm

11/12/2011 code-examplecpp

### # Summary

This is a computer graphics related algorithm that draws line using graphics in C language.

Using this algorithm we won't get the exact required line, there are in-built graphics functions present in graphics.h header that gives a more better line. But in-order to master algorithms we need to get a start with whatever we can learn with.

### # Code

``````#include "stdio.h"
#include "conio.h"
#include "graphics.h"
#include "math.h"
#define ROUND(a) ((int)(a+0.5))

void dda_line(int xa,int xb,int ya,int yb)
{
int dx,dy,i,length;
float ddx,ddy,x,y;

dx = xb - xa;
dy = yb - ya;

x = xa;
y = ya;
if(abs(dx) &gt; abs(dy))
{
length = abs(dx);
}
else
{
length = abs(dy);
}

ddx = abs(dx)/length;
ddy = abs(dy)/length;

putpixel(ROUND(x),ROUND(y),RED);
i=0;
while(i&lt;=length)
{
x = x + ddx;
y = y + ddy;
putpixel(ROUND(x),ROUND(y),RED);
i++;
}
putpixel(ROUND(x),ROUND(y),RED);
}

void main()
{
int xa,xb,ya,yb;
int gd,gm;
detectgraph(&gd,&gm);
gd = DETECT;
initgraph(&gd,&gm,"C:\TC\BGI");

printf("Enter start & end points:=&gt; ");
scanf("%d %d",&xa,&ya);
scanf("%d %d",&xb,&yb);

dda_line(xa,xb,ya,yb);
getch();
closegraph();
}
``````
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56