DDA algorithm not drawings lines for some coordinates?

1.6k views Asked by At

My code is working properly for slope=1 but not for other slopes. Its drawing either horizontal or vertical line for slopes other than 1. What is wrong with this code.Any help will be appreciated.

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

int main( )
{
int x,y,x1,y1,x2,y2,dx,dy;
float step;

int i,gd,gm;

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


detectgraph(&gd,&gm);
initgraph(&gd,&gm,"");

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,1);
      x=x+dx;
      y=y+dy;
      i=i+1;
      delay(100);
}
getch();
}
2

There are 2 answers

2
Michael Dorgan On
dx=dx/step;
dy=dy/step;

You've made step a float, but dx and dy are integer. As such, this divide is going to give you a 0 in one of these 2 values. I was under the impression that DDA routines were all integer so having the float in there at all makes me wonder. I'll look deeper at the algorithm and see what else I find.

Here's a routine that uses floats in a way that won't zero the step.

and another for windows.

1
Keval Doshi On

It seems that you are just accepting one value in the

scanf("%f%f",&x1);
scanf("%f%f",&y1);

statements. Try correcting that and running the code once again.