Digital Differential Analyzer (DDA) Line Drawing Algorithm [With C Code]

Digital Differential Analyzer (DDA) is a scan-conversion line drawing algorithm based on calculating either dx or dy using equation dy=mdx. Sampling line at unit intervals in one coordinate and determining corresponding integer values nearest the line path is done for other coordinate.

 

For a line of positive slope value less than or equal to 1, sampling is done at unit x intervals (dx=1) and corresponding y is calculated as yk+1=yk+m. Similarly, in case of slope greater than 1, dy=1 is kept sampling at unity intervals whereas each succeeding x value is calculated as: xk+1 = xk + 1/m.

 

Algorithm:

 

  • Define and input endpoints (x1,y1) and (x2,y2).
  • Calculate the distance between the two endpoints i.e dx=x2-x1 and dy=y2-y1.
  • If |dx|>|dy|:

 

           steps=dx

         else

           steps=dy

 

  • Compute:

 

          xinc=dx/steps

          yinc=dy/steps

 

  • Set x=x1, y=y1, k=0
  • Do:

 

         Plot(round(x),round(y))

            x=x+xinc

            y=y+yinc

            k=k+1

        while(k<=|steps|)

 

#include <graphics.h>

#include <stdio.h>

#include <math.h>

#include<conio.h>

void main()

{

float x,y,x1,y1,x2,y2,dx,dy,steps,xinc,yinc;

int k,gd,gm,xmax,ymax;

int gdriver=DETECT, gmode, errorcode;

initgraph(&gdriver, &gmode,”c:\TC\BGI\”);

printf(“Enter the value of x1, y1, x2 and y2 : “);

scanf(“%f %f %f %f”,&x1, &y1, &x2, &y2);

detectgraph(&gd,&gm);

initgraph(&gd,&gm,””);

dx=(x2-x1);

dy=(y2-y1);

if(fabs(dx)>=fabs(dy)){

steps=dx;

}

else {

steps=dy;

}

xinc=(dx/steps);

yinc=(dy/steps);

x=x1;

y=y1;

do

{

putpixel(x,y,1);

x=x+xinc;

y=y+yinc;

k=k+1;

}while(k<=fabs(steps));

getch();

 

}

 

We're always listening.
Have something to say about this article? Find us on Facebook, Twitter or our LinkedIn.
Raju Dawadi
Raju Dawadi
Raju is currently actively involved in DevOps world and is focused on Container based architecture & CI/CD automation along with Linux administration. Want to discuss with him on any cool topics? Feel free to connect on twitter, linkedIn, facebook.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.