Write a c program to implement DDA line drawing algorithm.
The Digital Differential Analyzer (DDA) algorithm is a simple and efficient line drawing algorithm used in computer graphics. It works by incrementing either the x or y coordinate by a small step based on the slope of the line. Below is a C program that implements the DDA line drawing algorithm:
#include <stdio.h>
#include <graphics.h>
#include <math.h>
// Function to implement DDA line drawing algorithm
void drawLineDDA(int x1, int y1, int x2, int y2) {
int dx = x2 - x1;
int dy = y2 - y1;
int steps;
// Determine the number of steps
if (abs(dx) > abs(dy)) {
steps = abs(dx);
} else {
steps = abs(dy);
}
// Calculate increments for x and y
float xIncrement = (float)dx / steps;
float yIncrement = (float)dy / steps;
// Initialize starting point
float x = x1;
float y = y1;
// Plot the first point
putpixel(round(x), round(y), WHITE);
// Loop to plot the line
for (int i = 1; i <= steps; i++) {
x += xIncrement;
y += yIncrement;
putpixel(round(x), round(y), WHITE);
}
}
int main() {
int gd = DETECT, gm;
int x1, y1, x2, y2;
// Initialize graphics mode
initgraph(&gd, &gm, NULL);
// Input coordinates of the two points
printf("Enter the coordinates of the first point (x1 y1): ");
scanf("%d %d", &x1, &y1);
printf("Enter the coordinates of the second point (x2 y2): ");
scanf("%d %d", &x2, &y2);
// Draw the line using DDA algorithm
drawLineDDA(x1, y1, x2, y2);
// Wait for a key press
getch();
// Close the graphics mode
closegraph();
return 0;
}