Objective
Write a C# Struct to store data of 2D points. The fields for each point will be:
x coordinate (short)
y coordinate (short)
r (red colour, byte)
g (green colour, byte)
b (blue colour, byte)
Write a C# program which creates two "points", asks the user for their data, and then displays their content.
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace for basic functionality
// Define the Point struct to store 2D point data and RGB color information
struct Point
{
public short x; // X-coordinate of the point (short type)
public short y; // Y-coordinate of the point (short type)
public byte r; // Red color component (byte type)
public byte g; // Green color component (byte type)
public byte b; // Blue color component (byte type)
}
class Program // Define the main class
{
static void Main() // The entry point of the program
{
// Create two instances of the Point struct
Point point1, point2;
// Ask the user for the data of the first point
Console.WriteLine("Enter data for Point 1:");
Console.Write("Enter X coordinate: ");
point1.x = short.Parse(Console.ReadLine()); // Get the X coordinate for point1
Console.Write("Enter Y coordinate: ");
point1.y = short.Parse(Console.ReadLine()); // Get the Y coordinate for point1
Console.Write("Enter Red color value (0-255): ");
point1.r = byte.Parse(Console.ReadLine()); // Get the red color component for point1
Console.Write("Enter Green color value (0-255): ");
point1.g = byte.Parse(Console.ReadLine()); // Get the green color component for point1
Console.Write("Enter Blue color value (0-255): ");
point1.b = byte.Parse(Console.ReadLine()); // Get the blue color component for point1
// Ask the user for the data of the second point
Console.WriteLine("\nEnter data for Point 2:");
Console.Write("Enter X coordinate: ");
point2.x = short.Parse(Console.ReadLine()); // Get the X coordinate for point2
Console.Write("Enter Y coordinate: ");
point2.y = short.Parse(Console.ReadLine()); // Get the Y coordinate for point2
Console.Write("Enter Red color value (0-255): ");
point2.r = byte.Parse(Console.ReadLine()); // Get the red color component for point2
Console.Write("Enter Green color value (0-255): ");
point2.g = byte.Parse(Console.ReadLine()); // Get the green color component for point2
Console.Write("Enter Blue color value (0-255): ");
point2.b = byte.Parse(Console.ReadLine()); // Get the blue color component for point2
// Display the contents of both points
Console.WriteLine("\nPoint 1 Data:");
Console.WriteLine($"X: {point1.x}, Y: {point1.y}, Color: RGB({point1.r}, {point1.g}, {point1.b})");
Console.WriteLine("\nPoint 2 Data:");
Console.WriteLine($"X: {point2.x}, Y: {point2.y}, Color: RGB({point2.r}, {point2.g}, {point2.b})");
}
}