Create a class named Square that contains fields for area and the length of a side and whose constructor requires a parameter for the length of one side of a Square. The constructor assigns its parameter to the length of the Square’s side field and calls a private method that computes the area field. Also include read-only properties to get a Square’s side and area. Create a class named Demo Squares that instantiates an array of ten Square objects with sides that have values of 1 through10. Display the values for each Square. Save the class as DemoSquares.cs.
Loading

Tahir AnsariRank #366 · 6.8K reputationPosted Sep 1, 2023, 1:17 AM EDT
using System; public class Square { private double side; private double area; public Square(double sideLength) { side = sideLength; CalculateArea(); } private void CalculateArea() { area = side * side; } public double Side { get { return side; } } public double Area { get { return area; } } } public class DemoSquares { public static void Main(string[] args) { Square[] squares = new Square[10]; // Instantiate Square objects with sides from 1 to 10 for (int i = 0; i < squares.Length; i++) { double sideLength = i + 1; // Sides range from 1 to 10 squares[i] = new Square(sideLength); } // Display the values for each Square Console.WriteLine("Squares:"); for (int i = 0; i < squares.Length; i++) { Console.WriteLine($"Side: {squares[i].Side}, Area: {squares[i].Area}"); } } }Abhishek YadavRank #217 · 11.3K reputationPosted Sep 1, 2023, 2:20 AM EDT
Here is the code for the classes Square and DemoSquares:
using System; public class Square { private double side; private double area; public double Side { get { return side; } } public double Area { get { return area; } } public Square(double sideLength) { side = sideLength; CalculateArea(); } private void CalculateArea() { area = side * side; } } public class DemoSquares { public static void Main(string[] args) { Square[] squares = new Square[10]; for (int i = 0; i < squares.Length; i++) { squares[i] = new Square(i + 1); } foreach (Square square in squares) { Console.WriteLine("Side: {0}, Area: {1}", square.Side, square.Area); } } }In the
Squareclass, there are private fieldssideandarea, representing the length of a side and the area of the square respectively. The constructor takes a parameter for the length of one side of the square, assigns it to thesidefield, and then calls theCalculateArea()method to compute the area. TheSideandAreaproperties are read-only properties that allow external access to the values ofsideandarea.The
DemoSquaresclass is where the actual demonstration of theSquareclass takes place. It instantiates an array of tenSquareobjects, with side lengths ranging from 1 to 10. Then, it iterates over the array and displays the values for each square, including its side length and area.Note that you need to save the
DemoSquaresclass asDemoSquares.csfor it to compile and run as a standalone program.