Graphics 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Aqsa,22DCS008

Practical:-03

Objective:- Write a program in C to implement Bresenham’s line drawing and DDA


algorithm, and compare the results with each other.

//Program for DDA (Digital Differential Analyzer) Line Drawing Algorithm:-

#include <stdio.h>
#include <graphics.h>

#include <math.h>

void drawLineDDA(int x1, int y1, int x2, int y2) {

int dx = x2 - x1, dy = y2 - y1; int steps =

abs(dx) > abs(dy) ? abs(dx) : abs(dy);

float xIncrement = dx / (float) steps;

float yIncrement = dy / (float) steps;

float x = x1, y = y1; putpixel(round(x), round(y),

WHITE); // Initial point

for (int i = 0; i <= steps; i++) { x += xIncrement;

y += yIncrement; putpixel(round(x), round(y),

WHITE); // Plot each pixel delay(10); // Add delay for

visualization

}
} int main() { int gd = DETECT, gm;

initgraph(&gd, &gm, NULL); int x1 =

100, y1 = 100, x2 = 300, y2 = 250;

drawLineDDA(x1, y1, x2, y2);


Aqsa,22DCS008
Practical:-03

getch();

closegraph();

return 0; }

Output:-

//Program for Bresenham’s line Drawing Algorithm:-

#include <stdio.h>
#include <graphics.h>

#include <math.h>

#include <stdlib.h>

// Function to implement Bresenham's Line Drawing

Algorithm void drawLineBresenham(int x1, int y1, int x2, int

y2) { int dx = abs(x2 - x1), dy = abs(y2 - y1); int sx = (x1

< x2) ? 1 : -1; int sy = (y1 < y2) ? 1 : -1; int err = dx - dy;

while (1) { putpixel(x1, y1, WHITE); // Plot the

current pixel if (x1 == x2 && y1 == y2) break;


Aqsa,22DCS008
Practical:-03

int e2 = 2 * err;

if (e2 > -dy) {

err -= dy; x1

+= sx; } if

(e2 < dx)

{ err += dx;

y1 += sy;

}
delay(5); // Optional delay for visualization
}
} int main() { int gd =

DETECT, gm;

initgraph(&gd, &gm, NULL);

int x1, y1, x2, y2;

// Input start and end points of the line

printf("Enter the starting point of the line (x1, y1): ");

scanf("%d %d", &x1, &y1); printf("Enter the ending

point of the line (x2, y2): "); scanf("%d %d", &x2,

&y2);

drawLineBresenham(x1, y1, x2, y2);


getch();
closegraph();

return 0; }

Output:-
Aqsa,22DCS008
Practical:-03

Comparison of Results:

• DDA:

o Uses floating-point arithmetic and slope calculation.

o May produce slight inaccuracies due to rounding when plotting points.

o Less efficient due to floating-point operations.

• Bresenham’s:

o Uses only integer arithmetic, making it more efficient.


o Generally more accurate, especially when drawing lines with steep slopes
or non-integer coordinates.
o Faster due to the absence of floating-point operations.

You might also like