Question 1 Draw a Circle 50 points Before starting this ques
Solution
I\'ve also included the main function, so that you can test the code.
public class Circle {
public static void main(String[] args)
{
// Main function for testing
drawCircle(1,3,3,\'&\');
drawCircle(3,3,3,\'&\');
drawCircle(4,10,5,\'&\');
drawCircle(5,10,12,\'&\');
//drawCircle(5,2,2,\'&\');
//drawCircle(-5,7,12,\'&\');
}
/*
* This function checks whether a point lies on the circle or not. If the point lies on the circle
* the function returns true, else false
* Input : radius, x ,y (centre of circle), pt_x, pt_y (point which is checked)
* Returns : boolean
*/
public static boolean onCircle(int radius,int x,int y,int pt_x,int pt_y){
int d = ( (pt_x - x) * (pt_x - x) ) + ( (pt_y - y) * (pt_y - y));
int rad_sq = radius * radius;
if(d >= rad_sq && d<= rad_sq + 1)
{
// point lies on the circle
return true;
}
// point does not lie on the circle
return false;
}
public static void verifyInput(int radius,int x,int y){
if(radius < 0 )
throw new IllegalArgumentException(\"Circle must have positive radius\");
//checks if circle fits in first quadrant
if(radius > x || radius > y)
throw new IllegalArgumentException(\"Circle must fit in upper right quadrant\");
}
public static void drawCircle(int radius,int x,int y,char c)
{
// check the user input
verifyInput(radius,x,y);
int y_axis = 9;
int x_axis = 9;
if(y+radius > 9)
{
y_axis = y + radius;
}
if(x+radius > 9)
{
x_axis = x + radius;
}
for(int i = y_axis; i >= 0 ;i--)
{
for(int j=0;j<=x_axis ;j++){
if(i== y_axis && j==0)
System.out.print(\"^\");
if(onCircle(radius,x,y,j,i))
System.out.print(c);
else if(i==0 && j==0)
{
System.out.print(\'+\');
}
else if(j==0 && i!=y_axis){
System.out.print(\'|\');
}
else if(i==0 && j==x_axis){
System.out.print(\'>\');
}
else if(i==0){
System.out.print(\'-\');
}
else
System.out.print(\" \");
}
System.out.println(); // new line
}
}
}


