Tuesday, December 19, 2017

C++ program to draw a circle and ellipse in a single window (using graphics.h)

















#include <graphics.h>
#include <iostream>
#include <conio.h>
using namespace std;
void circle();
void ellipse();
void plotpoints(int,int,int,int);
int main(){

int gdriver = DETECT, gmode;
initgraph(&gdriver,&gmode,"c:\\turboc3\\bgi");

circle();

ellipse();
getch();
closegraph();
return 0;
}

void circle()
{
    int x,y,p,xc,yc,r;
    cout<<"Enter co-ordinate for centre of circle:";
cin>>xc>>yc;
cout<<"Enter radius of circle: ";
cin>>r;

x = 0;
y = r;
p = 1-r;
while(x<=y){
if(p<0){
x=x+1;
y=y+0;
p=p+2*x +1;
}
else{
x=x+1;
y=y-1;
p=p+2*x-2*y+1;
}
putpixel(xc+x,yc+y,WHITE);
putpixel(xc+y,yc+x,WHITE);
putpixel(xc+x,yc-y,WHITE);
putpixel(xc+y,yc-x,WHITE);
putpixel(xc-x,yc-y,WHITE);
putpixel(xc-y,yc-x,WHITE);
putpixel(xc-x,yc+y,WHITE);
putpixel(xc-y,yc+x,WHITE);
delay(50);
}
}

void ellipse()
{
    int x,y,p,xc,yc,rx,ry;
    cout<<"Enter co-ordinate for centre of ellipse:";
cin>>xc>>yc;
cout<<"Enter the value of rx and ry of ellipse: ";
cin>>rx>>ry;
x=0;
y=ry;
p=ry*ry-ry*rx*rx+(1/4)*rx*rx;
while((2*ry*ry*x)<(2*rx*rx*y))
{
    if(p<0)
    {
        p=p+2*x*ry*ry+ry*ry;
        x=x+1;
        y=y+0;

    }
    else
    {
        p=p-2*y*rx*rx+2*x*ry*ry+ry*ry;
        x=x+1;
        y=y-1;
    }

    plotpoints(x,y,xc,yc);

}
p=(x+0.5)*(x+0.5)*ry*ry+rx*rx*(y-1)*(y-1)-rx*rx*ry*ry;
while(y>0)
{
    if(p<0)
    {
        x=x+1;
        y=y-1;
        p=p+2*x*ry*ry+rx*rx-2*y*rx*rx;
    }
    else
    {
        x=x+0;
        y=y-1;
        p=p+rx*rx-2*y*rx*rx;
    }
plotpoints(x,y,xc,yc);


}

}
void plotpoints(int x,int y,int xc,int yc)
{
    putpixel(x+xc,y+yc,WHITE);
    putpixel(-x+xc,y+yc,WHITE);
    putpixel(x+xc,-y+yc,WHITE);
    putpixel(-x+xc,-y+yc,WHITE);
    delay(50);
}
                                                                                                                                                                                                                       

1 comment: