Name: Title:

 Name:
ONLINE COMPILERS
LIBRARY
MANUAL PAGES & DOCS
CONTACT

User Submitted Source Code!

Description:
dda
Language: C/C++
Code:
/*// ---------------Assignment No.1----------------
//Title:- Write C++ program to draw line using DDA and Bresenhams algo. Inherit pixel class and use function overloading*/

#include<iostream>
#include<stdlib.h>
#include<graphics.h> //header file for switching text to graphics mode
#include<math.h>

using namespace std;
class Line
{
int s1,s2;
public:
void dda();
int sign(float);
void bresenhams();
};

void Line::dda()   //DDA Algorithm
{
int x1,x2,y1,y2;

//Step1: read end points of line
cout<<"Enter the X1 and Y1 co-ordiates::";   cin>>x1>>y1;
cout<<"Enter the X2 and Y2 co-ordiates::";   cin>>x2>>y2;

int i,length,dx,dy;
float x,y,xinc,yinc,temp1;

//Step 2: find dx and dy
dx=abs(x2-x1);
dy=abs(y2-y1);

//Step 3:decide in which direction to move
if(dx>=dy)
length=dx;
else
length=dy;

//Step 4: find increment value for x and y
xinc=(float)(x2-x1)/length;
yinc=(float)(y2-y1)/length;
s1=sign(xinc);
s2=sign(yinc);

//Step 5: Plot first pixel
x=x1+(0.5*s1);
y=y1+(0.5*s2);;
putpixel(x,y,WHITE); //plot first pixel

//Step 6:
for(i=1;i<=length;i++)
{
x=x+xinc;
y=y+yinc;
putpixel(x,y,WHITE);

}

}

//Sign function
int Line::sign(float temp)
{
if(temp==0) return 0;
else if(temp>0) return 1;
else return -1;
}

void Line::bresenhams()
{
int x1,x2,y1,y2,exchange,i,dx,dy, temp,length;
float e,x,y;
//Step1: read end points of line
cout<<"Enter the X1 and Y1 co-ordiates::";   cin>>x1>>y1;
cout<<"Enter the X2 and Y2 co-ordiates::";   cin>>x2>>y2;

//Step 2: find dx and dy
dx = abs(x2-x1);
dy = abs(y2-y1);
//Step 3: Initialize starting point
x=x1;
y=y1;
//Step 4: find s1 and s2 to find in which quadrant line to be drawn

s1=sign(x2-x1);
s2=sign(y2-y1);
//Step 5:decide in which direction to move
if(dy>dx)
{
exchange=1;
length=dy;
}
else
{
exchange=0;
length=dx;
}

//Step 6: find decision variable
e = 2*dy-dx;

//Step 7:
i=1;
do
{
putpixel(x,y,WHITE);
while(e>=0)
{

if(exchange==1)
x=x+s1;
else
y=y+s2;
e = e - 2*dx;
putpixel(x,y,WHITE);
}

if(exchange==1)
y=y+s2;
else
x=x+s1;
e = e + 2*dy;
i++;
}while(i<=length);
}

int main()
{
Line s;
int ch;
char a;
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);

do
{
cout<<"_____________________";
cout<<"n1. DDA Algorithm::";
cout<<"n2. BRESANHAM's Algorithm::n";
cout<<"_____________________";
cout<<"nEnter ur choice::t";     cin>>ch;

switch(ch)
{
case 1:
s.dda();
break;

case 2:
s.bresenhams();
break;

}
cout<<"nndo u want to continue(y/n)::";
cin>>a;
}while(a=='y');

}

/*------Output--------

[email protected]:~\$ cd cg
[email protected]:~/cg\$ g++ ass1.cpp -lgraph
[email protected]:~/cg\$ ./a.out
_____________________
1. DDA Algorithm::
2. BRESANHAM's Algorithm::
_____________________
Enter ur choice::
1
Enter the X1 and Y1 co-ordiates::100 100
Enter the X2 and Y2 co-ordiates::300 300

do u want to continue(y/n)::

*/