DDA Line Drawing Algorithm in C and C++
Here, you will know about DDA line drawing algorithm, and get the example code of DDA line drawing algorithm in c and c++ using computer graphics.
DDA Line Drawing Algorithm in C
The Digital Differential Analyzer(DDA) Line Drawing Algorithm is used to draw a line on computer screen. DDA is one of the earliest computer graphics algorithm. It was created by J.E. Bresenham in 1962.
DDA is an easy algorithm to calculate the points on the line using integer arithmetic.
DDA works by calculating the difference in y and x between the two points. It then calculates the incremental change values for each x and y pixel.
DDA Line Drawing Algorithm Example in C
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 | #include <graphics.h> #include <stdio.h> #include <math.h> #include <dos.h> void main() { float x,y,x1,y1,x2,y2,dx,dy,step; int i=1,gd=DETECT,gm; initgraph(&gd,&gm,"c:\\turboc3\\bgi"); printf("Enter the value of x1 and y1 : "); scanf("%f%f",&x1,&y1); printf("Enter the value of x2 and y2: "); scanf("%f%f",&x2,&y2); dx=abs(x2-x1); dy=abs(y2-y1); if(dx>=dy) step=dx; else step=dy; dx=dx/step; dy=dy/step; x=x1; y=y1; while(i<=step) { putpixel(x,y,15); x=x+dx; y=y+dy; i=i+1; } getch(); closegraph(); } |
DDA Line Drawing Algorithm Example in C++
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 | #include <graphics.h> #include <iostream.h.h> #include <math.h> #include <dos.h> void main() { float x,y,x1,y1,x2,y2,dx,dy,step; int i=1,gd=DETECT,gm; initgraph(&gd,&gm,"c:\\turboc3\\bgi"); cout<<"Enter the value of x1 and y1 : "; cin>>x1<<y1; cout<<"Enter the value of x2 and y2: "; cin<<x2<<y2; dx=abs(x2-x1); dy=abs(y2-y1); if(dx>=dy) step=dx; else step=dy; dx=dx/step; dy=dy/step; x=x1; y=y1; while(i<=step) { putpixel(x,y,15); x=x+dx; y=y+dy; i=i+1; } getch(); closegraph(); } |
Output :
Other Line Drawing Algorithms
1. Bresenham Line Drawing Algorithm
2. Mid Point Line Drawing Algorithm