Sunday, November 27, 2011

Implementation of Midpoint Circle Algorithm

 The Algorithm
 
function line(x0, y0, x1, y1)
   dx := abs(x1-x0)
   dy := abs(y1-y0) 
   if x0 < x1 then sx := 1 else sx := -1
   if y0 < y1 then sy := 1 else sy := -1
   err := dx-dy
 
   loop
     setPixel(x0,y0)
     if x0 = x1 and y0 = y1 exit loop
     e2 := 2*err
     if e2 > -dy then 
       err := err - dy
       x0 := x0 + sx
     end if
     if e2 <  dx then 
       err := err + dx
       y0 := y0 + sy 
     end if
   end loop
 
 
 The Program 
 
 #include<iostream.h>
     #include<conio.h>
     #include<graphics.h>
     #include<math.h>
     #include<dos.h>
     void main()
     { int dx,dy,s1,s2,x1,x2,y1,y2,x,y,temp,e,i,c;
      cout<<"enter the coordinates of the line in the form x1 x2 y1 y2\n";
      cin>>x1>>y1>>x2>>y2;
      int gdriver=DETECT,gmode;
      initgraph(&gdriver,&gmode,"");
      x=x1;y=y1;
      dx=abs(x2-x1);
      dy=abs(y2-y1);
      if(x2>x1)
 s1=1;
 else s1=-1;
      if(y2>y1)
      s2=1;
      else s2=-1;
  if(dy>dx)
  { temp=dx;
  dx=dy;
  dy=temp;
  c=1;
  }
  else c=0;

  e=2*dy-dx;
  for(i=1;i<=dx;i++)
  {  delay(40);
   putpixel(x,y,10);
    while(e>0)
     { if(c==1)
 { x+=s1;}
       else y=y+s2;
 e-=2*dx;
     }
    if(c==1)
     y+=s2;
    else
     x=x+s1;
  e+=2*dy;
  }
  getch();
}