Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

DDA Line Drawing Algorithm in C and C++

$
0
0

Here you will learn about dda line drawing algorithm in C and C++.

In Computer Graphics the first basic line drawing algorithm is Digital Differential Analyzer (DDA) Algorithm.

A line connects two points. It is a basic element in graphics. To draw a line, you need two points between which you can draw a line.

Also Read: Bresenham’s Line Drawing Algorithm in C and C++

Digital Differential Analyzer (DDA) Algorithm

Step 1: Read the input of the 2 end points of the line as (x1, y1) & (x2, y2) such that x1 != x2 and y1 != y2

Step 2: Calculate dx = x2 – x1 and dy = y2 – y1

Step 3:

if(dx>=dy)

step=dx

else

step=dy

Step 4: xin = dx / step & yin = dy / step

Step 5: x = x1 + 0.5 & y = y1 + 0.5

Step 6: 

for(k = 0; k < step; k++)

{

x = x + xin

y = y + yin

putpixel(x, y)

}

Program for DDA Line Drawing Algorithm in C

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

void main( )
{
	float x,y,x1,y1,x2,y2,dx,dy,step;
	int i,gd=DETECT,gm;

	initgraph(&gd,&gm,"c:\\turboc3\\bgi");

	printf("Enter the value of x1 and y1 : ");
	scanf("%f%f",&x1,&y1);
	printf("Enter the value of x2 and y2: ");
	scanf("%f%f",&x2,&y2);

	dx=abs(x2-x1);
	dy=abs(y2-y1);

	if(dx>=dy)
		step=dx;
	else
		step=dy;

	dx=dx/step;
	dy=dy/step;

	x=x1;
	y=y1;

	i=1;
	while(i<=step)
	{
		putpixel(x,y,5);
		x=x+dx;
		y=y+dy;
		i=i+1;
		delay(100);
	}

	closegraph();
}

Outptut

DDA Line Drawing Algorithm in C and C++

Program for DDA Line Drawing Algorithm in C++

#include <graphics.h>
#include <iostream.h>
#include <math.h>
#include <dos.h>

void main( )
{
	float x,y,x1,y1,x2,y2,dx,dy,step;
	int i,gd=DETECT,gm;

	initgraph(&gd,&gm,"c:\\turboc3\\bgi");

	cout<<"Enter the value of x1 and y1 : ";
	cin>>x1>>y1;
	cout<<"Enter the value of x2 and y2: ";
	cin>>x2>>y2;

	dx=abs(x2-x1);
	dy=abs(y2-y1);

	if(dx>=dy)
		step=dx;
	else
		step=dy;

	dx=dx/step;
	dy=dy/step;

	x=x1;
	y=y1;

	i=1;
	while(i<=step)
	{
		putpixel(x,y,5);
		x=x+dx;
		y=y+dy;
		i=i+1;
		delay(100);
	}

	closegraph();
}

Comment below if you have any doubts related above algorithm.

The post DDA Line Drawing Algorithm in C and C++ appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles