DDA algorithm program in c with program Code and Explanation

Below is a C program to implement the DDA (Digital Differential Analyzer) line drawing algorithm. DDA is a very simple line drawing algorithm that is used to draw a line on a 2D plane using two specified points like (xa, ya) and (xb, yb).

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 :
  1. At the very start of the program, It includes necessary header files and declares the "line_dda()" function.
  2. 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).
  3. 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.
  4. 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.
  5. To plot the graph, we require a number of steps, which will be determined by the maximum absolute difference between Dx and Dy.
  6. The increment values of xin and yin will be calculated by the ratios Dx/steps and Dy/steps.
  7. Initial point (xa, ya) will get plotted on the screen using the putpixel() function.
  8. 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.

Post a Comment

0 Comments