Chapter 6 - Circle
Chapter 6 - Circle
Exercise 1
Create in C# a class ‘Circle’ containing 3 private instance variables (coordinates x and y of the
center and the radius), the get and set methods and a constructor to initialize them, and override
the method ToString.
Define 2 methods in the class ‘Circle’ to return the perimeter and the area of the circle.
In a class Program which contains a method Main, create two instances A and B of type circle,
the information about the circles is given by the user, then calculate and display their
coordinates, radius, areas and perimeters.
(ExerciseCircle)
class Circle
{
private double x, y, r;
//constructor
public Circle(double x, double y, double r)
{
this.x = x; this.y = y;
if (r > 0)
this.r = r;
}
//properties
public double X
{
get { return x; }
set { x = value; }
}
public double Y
{
get { return y; }
set { y = value; }
}
public double R
{
get { return r; }
set
{
if (value > 0)
r = value;
}
}
public override string ToString()
{
return "Center : (" + x + "," + y + ") \nRadius : " + r +
"\n";
}
public double perimeter()
{
return 2 * r * Math.PI;
}
public double area()
{
return r * r * Math.PI;
}
}
class Program
{
static void Main(string[] args)
{
double x, y, r;
Console.Write("Give x, y, and r :");
x = double.Parse(Console.ReadLine());
y = double.Parse(Console.ReadLine());
r = double.Parse(Console.ReadLine());
Circle A = new Circle(x, y, r);
Console.Write("Give x, y, and r :");
x = double.Parse(Console.ReadLine());
y = double.Parse(Console.ReadLine());
r = double.Parse(Console.ReadLine());
Circle B = new Circle(x, y, r);
Console.WriteLine("Circle A:\n" + A);
Console.WriteLine(A.perimeter());
Console.WriteLine(A.area());
Console.WriteLine("Circle B:\n" + B);
Console.WriteLine(B.perimeter());
Console.WriteLine(B.area());
Console.ReadKey();
}
}