Sem 4‎ > ‎CG LAB‎ > ‎

### P4: WAP to draw a line using Bresenham's Algo

posted Jan 8, 2012, 8:19 AM by Neil Mathew
 SOURCE CODE:```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 #include #include #include #include   void LINE(int x1, int y1, int x2, int y2) { int x=x1; int y=y1;   int dx=abs(x2-x1); int dy=abs(y2-y1);   int Sx=abs(x2-x1)/(x2-x1);  //Sign int Sy=abs(y2-y1)/(x2-x1);   int steps,flag;   //Determining Greater length if(dy > dx) { steps=dy; flag=1;   //Swapping dx dy int t=dx; dx=dy; dy=t; } else { steps=dx; flag=0; }   //Decision variable int P=2*dy-dx;   //First Pixel putpixel(x,y,WHITE);   //Other Pixels: for(int i=1; i<=steps; i++) {   while( P > 0 ) {   if(flag==1) x=x+Sx; else y=y+Sy;   P=P-2*dx; } //END OF WHILE   if(flag==1) y=y+Sy; else x=x+Sx;   P=P+2*dy;   putpixel(x,y,WHITE);   } //END OF FOR   }       void main() { int gdriver=DETECT, gmode; initgraph(&gdriver, &gmode, "C:/TC/BGI");   int x1,x2,y1,y2; setbkcolor(DARKGRAY); setcolor(WHITE);   cout<<"\n Enter the Initial X Y Coordinate: "; cin>>x1>>y1;   cout<<"\n Enter the Final X Y Coordinate: "; cin>>x2>>y2;   cout<<"\n Press Enter to draw line."; getch();   outtextxy(x1-10,y1-10, "START"); LINE(x1,y1,x2,y2); outtextxy(x2+10,y2+10, "END"); getch(); closegraph(); }```OUTPUT: