C# Exercise: 81 Array of struct and menu

In this C# exercise, you are asked to expand the previous exercise (array of points) so that the program displays an interactive menu. The menu should allow the user to choose from the following options:

- Add data for one point.
- Display all the entered points.
- Calculate (and display) the average values for x and y.
- Exit the program.

This exercise will help you learn how to create interactive menus in a C# program, which is very useful for providing a user-friendly interface. Additionally, you will practice working with arrays and calculating average values, which will help you improve your skills in structured programming and data handling.

 Exercise

Array of struct and menu

 Objetive

Write a C# program that expand the previous exercise (array of points), so that it displays a menu, in which the user can choose to:

- Add data for one point
- Display all the entered points
- Calculate (and display) the average values for x and y
- Exit the program

 Example Code

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
    {
        // Define an array of Point structs with a size of 1000 to store up to 1000 points
        Point[] points = new Point[1000];
        int pointCount = 0;  // Initialize the counter for the number of points entered

        bool exit = false;  // Variable to control the exit condition of the loop

        // Menu loop to repeatedly show the options until the user chooses to exit
        while (!exit)
        {
            // Display the menu with options
            Console.WriteLine("\nMenu:");
            Console.WriteLine("1. Add data for one point");
            Console.WriteLine("2. Display all entered points");
            Console.WriteLine("3. Calculate and display average values for x and y");
            Console.WriteLine("4. Exit");
            Console.Write("Choose an option (1-4): ");

            // Read the user's menu choice
            string choice = Console.ReadLine();

            // Perform actions based on the user's choice
            switch (choice)
            {
                case "1":
                    // Add data for one point
                    if (pointCount < points.Length)
                    {
                        Console.WriteLine("\nEnter data for Point " + (pointCount + 1) + ":");

                        Console.Write("Enter X coordinate: ");
                        points[pointCount].x = short.Parse(Console.ReadLine());  // Get the X coordinate

                        Console.Write("Enter Y coordinate: ");
                        points[pointCount].y = short.Parse(Console.ReadLine());  // Get the Y coordinate

                        Console.Write("Enter Red color value (0-255): ");
                        points[pointCount].r = byte.Parse(Console.ReadLine());  // Get the red color component

                        Console.Write("Enter Green color value (0-255): ");
                        points[pointCount].g = byte.Parse(Console.ReadLine());  // Get the green color component

                        Console.Write("Enter Blue color value (0-255): ");
                        points[pointCount].b = byte.Parse(Console.ReadLine());  // Get the blue color component

                        pointCount++;  // Increment the counter for the number of points entered
                    }
                    else
                    {
                        Console.WriteLine("Maximum number of points reached.");
                    }
                    break;

                case "2":
                    // Display all entered points
                    if (pointCount > 0)
                    {
                        Console.WriteLine("\nEntered Points:");
                        for (int i = 0; i < pointCount; i++)
                        {
                            Console.WriteLine($"Point {i + 1}: X = {points[i].x}, Y = {points[i].y}, Color = RGB({points[i].r}, {points[i].g}, {points[i].b})");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No points entered yet.");
                    }
                    break;

                case "3":
                    // Calculate and display the average values for x and y
                    if (pointCount > 0)
                    {
                        float sumX = 0, sumY = 0;
                        for (int i = 0; i < pointCount; i++)
                        {
                            sumX += points[i].x;  // Sum of X coordinates
                            sumY += points[i].y;  // Sum of Y coordinates
                        }

                        float avgX = sumX / pointCount;  // Calculate average of X
                        float avgY = sumY / pointCount;  // Calculate average of Y

                        Console.WriteLine($"\nAverage X: {avgX:F2}");
                        Console.WriteLine($"Average Y: {avgY:F2}");
                    }
                    else
                    {
                        Console.WriteLine("No points entered yet to calculate averages.");
                    }
                    break;

                case "4":
                    // Exit the program
                    exit = true;
                    Console.WriteLine("Exiting the program.");
                    break;

                default:
                    // Handle invalid menu choices
                    Console.WriteLine("Invalid choice, please select a valid option.");
                    break;
            }
        }
    }
}

More C# Exercises of Arrays, Structures and Strings

 Reverse array
Write a C# program to ask the user for 5 numbers, store them in an array and show them in reverse order....
 Search in array
Write a C# program that says if a data belongs in a list that was previously created. The steps to take are: - Ask the user how many data will he ...
 Array of even numbers
Write a C# program to ask the user for 10 integer numbers and display the even ones....
 Array of positive and negative numbers
Write a C# program to ask the user for 10 real numbers and display the average of the positive ones and the average of the negative ones....
 Many numbers and sum
Write a C# program which asks the user for several numbers (until he enters "end" and displays their sum). When the execution is going to end, it must...
 Two dimensional array
Write a C# program to ask the user for marks for 20 pupils (2 groups of 10, using a two-dimensional array), and display the average for each group....
 Statistics V2
Write a C# statistical program which will allow the user to: - Add new data - See all data entered - Find an item, to see whether it has been en...
 Struct
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) ...
 Array of struct
Write a C# program that expand the previous exercise (struct point), so that up to 1.000 points can be stored, using an "array of struct". Ask the use...
 Books database
Create a small database, which will be used to store data about books. For a certain book, we want to keep the following information: Title Author...
 Triangle V2
Write a C# program to ask the user for his/her name and display a triangle with it, starting with 1 letter and growing until it has the full length: ...
 Rectangle V3
Write a C# program to ask the user for his/her name and a size, and display a hollow rectangle with it: Enter your name: Yo Enter size: 4 YoYoYoY...
 Centered triangle
Write a C# program that Display a centered triangle from a string entered by the user: __a__ _uan_ Juan...
 Cities database
Create a database to store information about cities. In a first approach, we will store only the name of each city and the number of inhabitants, a...
 Banner
Write a C# program to imitate the basic Unix SysV "banner" utility, able to display big texts....
 Triangle right side
Write a C# program that asks the user for a string and displays a right-aligned triangle: ____n ___an __uan Juan...
 Strings manipulation
Write a C# program that asks the user for a string and: - Replace all lowercase A by uppercase A, except if they are preceded with a space - Displ...
 Nested structs
Write a C# Struct to store two data for a person: name and date of birth. The date of birth must be another struct consisting on day, month an...
 Sort data
Write a C# program to ask the user for 10 integer numbers (from -1000 to 1000), sort them and display them sorted....
 Two dimensional array as buffer for screen
Write a C# program that declares a 70x20 two-dimensional array of characters, "draws" 80 letters (X, for example) in random positions and displays the...
 Two dimensional array 2: circunference on screen
Write a C# program that declares creates a 70x20 two-dimensional array of characters, "draws" a circumference or radius 8 inside it, and displays it o...
 Computer programs
Write a C# program that can store up to 1000 records of computer programs. For each program, you must keep the following data: * Name * Category ...
 Exercise tasks
Write a C# program that can store up to 2000 "to-do tasks". For each task, it must keep the following data: • Date (a set of 3 data: day, month and...
 Household accounts
Write a C# program in C# that can store up to 10000 costs and revenues, to create a small domestic accounting system. For each expense (or income), sh...