DDA Line Algorithm Program in C
Digital Differential Analyzer is an algorithm for drawing straight lines on a computer. This algorithm is very easy as it applies normal mathematical straight line equation formula. But to draw a line on a computer we need to do programs. DDA can be done with C, C++, and JAVA codes, but the main requirement is to do it in a C program.
In the C program of the DDA line, we must have to include graphics.h header file because the output will draw a line on the console.
The slope(m) is calculated by (y2-y1)/(x2-x1) where the two end points of the line are (x1,y1) and (x2,y2).
The algorithm states that if the slope(m) is less than 1 then increase x with 1 and increase y with the slope. If the slope(m) is greater than 1 then increase x with 1/slope(m) and increase y with 1. And if the slope is equal to 1 then increase both x and y with 1.
The below program is executed in the Turbo C environment. If you run this code in the Turbo C environment then you'll get the optimum output. To run in other compilers you must have to alter initgraph() function's path value.
C Program of DDA Line
#include <graphics.h>
#include <stdio.h>
#include <math.h>
#include <dos.h>
void main( )
{
float x,y,x1,y1,x2,y2,dx,dy,slope;
int i,gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi"); //Initialize the graphics function with path value
printf("Enter the value of x1 and y1 : "); //Take the points
scanf("%f%f",&x1,&y1);
printf("Enter the value of x2 and y2: ");
scanf("%f%f",&x2,&y2);
if(x2<x1 && y2<y1)
{
i=x1;
x1=x2;
x2=i;
i=y1;
y1=y2;
y2=i;
}
dx=abs(x2-x1);
dy=abs(y2-y1);
slope=dy/dx; //slope m = (y2-y1)/(x2-x1)
x=x1;
y=y1;
if(slope<1) //for slope less than 1 case
{
while(x<=x2) //run the loop until last point's x value is reached
{
putpixel(x,y,5);
x++;
y=y+slope;
delay(100); //delay the line printing by 100 ms
}
}
else if(slope>1) //for slope greater than 1 case
{
while(y<=y2)
{
putpixel(x,y,5);
x=x+(1/slope);
y++;
delay(100);
}
}
else //for slope equal to 1 case
{
while(x<=x2)
{
putpixel(x,y,5);
x++;
y++;
delay(100);
}
}
closegraph(); //close the graphics function
}
0 Comments