DDA algorithm program in c program:
#include<stdio.>
#include<math.h>
#include<conio.h>
#include<graphics.h>
#define round(val)(int)(val + 0.5)
void main() {
int gd = DETECT, gm;
void line_dda(int, int, int, int);
int xa, xb, ya, yb;
printf("Enter the two values");
scanf("%d%d%d%d", & xa, & ya, & xb, & yb);
initgraph( & gd, & gm, "");
cleardevice();
line_dda(xa, ya, xb, yb);
getch();
closegraph();
}
void line_dda(int xa, int ya, int xb, int yb) {
int Dx = xb - xa, Dy = yb - ya, steps, k;
float xin, yin, X = xa, Y = ya;
if (abs(Dx) > abs(Dy))
steps = abs(Dx);
else
steps = abs(Dy);
xin = Dx / (float) steps;
yin = Dy / (float) steps;
putpixel(round(X), round(Y), 6);
for (k = 0; k < steps; k++) {
X = X + xin;
Y = Y + yin;
putpixel(round(X), round(Y), 6);
}
}
Explanation of DDA algorithm program :
- At the very start of the program, It includes necessary header files and declares the "line_dda()" function.
- Next, the "main" function initializes the graphics mode using the "initgraph" function and takes input from the user for the two points (xa, ya) and (xb, yb).
- The line_dda(int xa,int ya,int xb,int yb) function is responsible for drawing a line between given points using the DDA algorithm.
- Inside the function line_dda(), Dx and Dy calculate the difference between the x- and y-coordinates of the two points. Like Dx=xb-xa and Dy=yb-ya.
- To plot the graph, we require a number of steps, which will be determined by the maximum absolute difference between Dx and Dy.
- The increment values of xin and yin will be calculated by the ratios Dx/steps and Dy/steps.
- Initial point (xa, ya) will get plotted on the screen using the putpixel() function.
- On each iteration, it increments the x-coordinate (X) by xin and the y-coordinate (Y) by yin. Then plots the current point (X, Y) using the putpixel function.
Note:
- The "int abs(int x)" is a standard function, which is available in the <stdlib.h> header. Which calculates the absolute value of an integer or a floating-point number.
- The "void putpixel (int x, int y, int color)" is a graphics programming function that is used to set the color of a single pixel at the given coordinates.
Understand Program example with Input and Output:
Input:
xa = 20, ya = 30 (Starting point)
xb = 80, yb = 90 (Ending point)
Output:
Once the inputs are taken from the user, it will plot a line on the graphics window between the points (20, 30) and (80, 90) using the DDA algorithm.
0 Comments