Tuesday, January 28, 2020

Midpoint circle drawing algorithm in C-Language

Midpoint circle drawing algorithm in C-Language:


Circle: it is locus of points equidistant  from  center . It means all points on circle are of distance r  from center point (xc,yc) in all sides.


Equation of circle with center (xc,yc) and radius r
    (x-xc)2+(y-yc)2=r2
 Center is at (0,0)
    x2+y2=r2     Where x and y is any point on circle

Symmetry of Circle:


Steps:

Step 1: Accept Center point (xc,yc)  of Circle and radius r of Circle.

Step 2: calculate initial decision parameter p=1-r

step 3:initiate x1=0 and y1=r;

Step 4: if p<0:

                                     x1=x1+1, y1=y1, P=P+2*x1+1

        else:
            x1=x1+1,y1=y1-1, p=p+2*x1+1-2*y1
Step 5: repeat step 3 until x1>=y1
Step 6: plot all points with respect to center point in all octants.
        putpixel(x1+xc,y1+yc,color);  
        putpixel(-x1+xc,y1+yc,color);
        putpixel(-x1+xc,-y1+yc,color);
        putpixel(x1+xc,-y1+yc,color);
        putpixel(y1+xc,x1+yc,color);
        putpixel(-y1+xc,x1+yc,color);
        putpixel(y1+xc,-x1+yc,color);
        putpixel(-y1+xc,-x1+yc,color);
Step 7: stop.

Program:


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

#include<conio.h>


void main()

{

int xc,yc,r,p,x1,y1;

int gd=DETECT,gm;

initgraph(&gd,&gm,"c:\\turboc3\\bgi");

printf("Enter center coorinates of Circle");

scanf("%d%d",&xc,&yc);

printf("Enter radius of circle");

scanf("%d",&r);

x1=0,y1=r;   //initialize x1 and y1
p=1-r;
do{
if(p<0)
{
 x1=x1+1;
 y1=y1;
 p=p+2*x1+1;
}
else
{
 x1=x1+1;
 y1=y1-1;
 p=p+2*x1+1-2*y1;
}
putpixel(x1+xc,y1+yc,4);  //putpixel for eight octants of circle
putpixel(-x1+xc,y1+yc,4);
putpixel(-x1+xc,-y1+yc,4);
putpixel(x1+xc,-y1+yc,4);
putpixel(y1+xc,x1+yc,4);
putpixel(-y1+xc,x1+yc,4);
putpixel(y1+xc,-x1+yc,4);
putpixel(-y1+xc,-x1+yc,4);

}while(x1<=y1);       // stop condition when x>=y
getch();


}

Output: