Exercise
Array Of Objects: Table
Objective
Create a class named "Table". It must have a constructor, indicating the width and height of the board. It will have a method "ShowData" which will write on the screen the width and that height of the table. Create an array containing 10 tables, with random sizes between 50 and 200 cm, and display all the data.
Write Your C# Exercise
C# Exercise Example
// Import the System namespace for basic functionality
using System;
public class ArrayOfObjectsDemo
{
// Define the Table class
public class Table
{
// Integer fields to store the width and height of the table
private int width;
private int height;
// Constructor to initialize the table's width and height
public Table(int tableWidth, int tableHeight)
{
// Set the width of the table
width = tableWidth;
// Set the height of the table
height = tableHeight;
}
// Method to show the table's width and height
public void ShowData()
{
// Display the width and height of the table
Console.WriteLine($"Width: {width} cm, Height: {height} cm");
}
}
// Define the Main entry point of the program for testing
public static void Main()
{
// Create an array to hold 10 Table objects
Table[] tables = new Table[10];
// Create a random number generator for generating table sizes
Random random = new Random();
// Loop to populate the array with 10 tables having random sizes between 50 and 200 cm
for (int i = 0; i < tables.Length; i++)
{
// Randomly generate width and height between 50 and 200 cm
int width = random.Next(50, 201);
int height = random.Next(50, 201);
// Create a new Table object with the generated width and height and add it to the array
tables[i] = new Table(width, height);
}
// Display the data for each table in the array
for (int i = 0; i < tables.Length; i++)
{
Console.WriteLine($"Table {i + 1}:");
// Call the ShowData method to display the table's dimensions
tables[i].ShowData();
Console.WriteLine(); // Print an empty line for separation
}
}
}