Skip to main content

DDA Line Drawing Algorithm Using C Programming

2 min read
Share:
On this page (5sections)

DDA Line Drawing Algorithm Using C Programming

In computer graphics, line drawing algorithms are used to generate lines and curves on a computer screen. The DDA (Digital Differential Analyzer) algorithm is a simple and efficient method for drawing lines. This blog post will provide an enhanced and explained version of the DDA line drawing algorithm implemented in C programming language. We will discuss the algorithm, its implementation, and provide a step-by-step explanation of the code.

Prerequisites

Before we dive into the implementation, make sure you have the necessary libraries installed. In this code, we are using the stdio.h, math.h, conio.h, and graphics.h libraries. The graphics.h library is used to create a graphical window for displaying the line.

Implementation

#include<stdio.h>
#include<math.h>
#include<graphics.h>
#define round(val) (int)(val+0.5)
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);
   }
}
int main() {
   int gd = DETECT, gm;
   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();
   return 0;
}

Explanation

Let’s go through the code and understand how the DDA line drawing algorithm works.

line_dda function

The line_dda function takes four parameters: xa, ya (starting point) and xb, yb (ending point). It draws the line using the DDA algorithm:

  1. Calculate Dx = xb - xa and Dy = yb - ya.
  2. Choose the number of steps as the larger of |Dx| and |Dy|.
  3. Compute per-step increments xin = Dx / steps and yin = Dy / steps.
  4. Plot the starting pixel, then update (X, Y) each step and call putpixel.

main function

  1. Initialize the graphics system with initgraph.
  2. Read the two endpoints from the user.
  3. Clear the screen with cleardevice.
  4. Call line_dda to draw the line.
  5. Wait for a key press and close the graphics window.

Related Tutorials

Search tutorials