Reputation: 87
I made this code. This code handles the case when dx and dy are greater than 0. But what to do, when one of them is less than 0. The algorithm says that m should be taken as absolute and x and y should be decremented. But how to decrement i(x) in the second for loop?
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <graphics.h>
void illuminate (int x, int y, int col)
{
putpixel(x+320,240-y,col);
}
void main (void)
{
int i,x1,y1,x2,y2,j;
float dx,dy,m,e;
int gdriver=DETECT,gmode;
initgraph(&gdriver,&gmode, "C:\\TurboC3\\BGI");
printf("\nEnter the coordinates of initial point\n");
scanf("%d%d",&x1,&y1);
printf("\nEnter the coordinates of final point\n");
scanf("%d%d",&x2,&y2);
dx = x2 - x1;
dy = y2 - y1;
m = abs(dy)/abs(dx);
j = y1;
e = m - 1;
line(320,0,320,480);
line(0,240,640,240);
if ( dx >= 0 && dy >= 0 )
{
for (i=x1;i<x2-1;i++)
{
illuminate(i,j,4);
if ( e>= 0 )
{
j = j+1;
e = e-1.0;
}
e = e+m;
}
}
else
{
for (i=x1;i<x2-1;i++)
{
illuminate(i,j,4);
if (e>=0)
{
j = j-1;
e = e-1.0;
}
e = e+m;
}
}
getch();
}
Upvotes: 1
Views: 1414
Reputation: 70929
One easy way to handle this case is to "draw" the mirror image of the line with respect to the x axis in some container and then mirror it again. You don't actually have to do that but this way of thinking may help you figure our where you should put negation. The code in the case when dx
is positive or negative is very similar and differs only at a few signs.
Upvotes: 1