Estadísticas V2 - Ejercicio de Programacion C# Sharp

En este ejercicio en C#, se te pide crear un programa estadístico que permita al usuario realizar las siguientes acciones:
- Agregar nuevos datos
- Ver todos los datos ingresados
- Buscar un dato para verificar si ha sido ingresado o no
- Ver un resumen de estadísticas: cantidad de datos, suma, promedio, máximo, mínimo
- Salir del programa
Estas opciones deben aparecer como un menú interactivo, donde cada opción será seleccionada mediante un número o una letra. El programa debe ser capaz de almacenar hasta 1000 datos, pero también debe llevar un conteo de cuántos datos han sido realmente ingresados.
Este ejercicio te permitirá trabajar con arreglos para almacenar los datos, así como con estructuras de control como el menú interactivo y las opciones para realizar cálculos estadísticos básicos, como la suma, el promedio, el máximo y el mínimo de los datos ingresados. Además, te ayudará a practicar el manejo de entradas de datos y la organización de menús en consola.
Este ejercicio es una excelente oportunidad para aprender a estructurar programas interactivos y realizar cálculos estadísticos en C#.

 Categoría

Matrices, Estructuras y Cadenas

 Ejercicio

Estadísticas V2

 Objectivo

Crear un programa en C# estadístico que permita al usuario:

- Añadir nuevos datos
- Ver todos los datos introducidos
- Buscar un artículo, para ver si se ha introducido o no
- Ver un resumen de estadísticas: cantidad de datos, suma, promedio, máximo, mínimo
- Salir del programa

Estas opciones deben aparecer como un menú. Cada opción será elegida por un número o una letra.

El programa debe reservar espacio para un máximo de 1000 datos, pero llevar un recuento de cuántos datos existen realmente.

 Ejemplo Ejercicio C#

 Copiar Código C#
using System;  // Import the System namespace for basic functionality

class Program  // Define the main class
{
    static void Main()  // The entry point of the program
    {
        double[] data = new double[1000];  // Create an array to store up to 1000 data points
        int count = 0;  // Variable to keep track of the number of data entries
        bool running = true;  // Variable to control the program's main loop

        // Display the menu to the user
        while (running)
        {
            Console.Clear();  // Clear the console screen before displaying the menu
            Console.WriteLine("Statistics Program");
            Console.WriteLine("1. Add new data");
            Console.WriteLine("2. See all data entered");
            Console.WriteLine("3. Find an item");
            Console.WriteLine("4. View statistics summary");
            Console.WriteLine("5. Exit");
            Console.Write("Please choose an option (1-5): ");  // Ask the user to choose an option

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

            switch (choice)  // Perform an action based on the user's choice
            {
                case "1":
                    // Add new data
                    if (count < 1000)  // Check if there's space for more data
                    {
                        Console.Write("Enter a number to add: ");  // Ask the user for a number
                        while (!double.TryParse(Console.ReadLine(), out data[count]) || data[count] < 0)  // Ensure valid input
                        {
                            Console.WriteLine("Invalid input. Please enter a valid number.");  // Handle invalid input
                            Console.Write("Enter a number to add: ");  // Prompt again for a valid input
                        }
                        count++;  // Increment the count after adding new data
                        Console.WriteLine("Data added successfully!");  // Inform the user that the data was added
                    }
                    else
                    {
                        Console.WriteLine("Maximum data limit reached.");  // Inform the user if the limit is reached
                    }
                    break;

                case "2":
                    // See all data entered
                    if (count > 0)  // Check if there is any data entered
                    {
                        Console.WriteLine("Entered data:");  // Inform the user that the entered data will be displayed
                        for (int i = 0; i < count; i++)  // Loop through the data array
                        {
                            Console.WriteLine(data[i]);  // Display each data entry
                        }
                    }
                    else
                    {
                        Console.WriteLine("No data entered yet.");  // Inform the user if no data was entered
                    }
                    break;

                case "3":
                    // Find an item
                    Console.Write("Enter a number to search for: ");  // Ask the user for a number to search
                    double searchValue;  // Variable to store the search value
                    while (!double.TryParse(Console.ReadLine(), out searchValue))  // Ensure valid input
                    {
                        Console.WriteLine("Invalid input. Please enter a valid number.");  // Handle invalid input
                        Console.Write("Enter a number to search for: ");  // Prompt again for a valid input
                    }
                    bool found = false;  // Variable to track if the number is found
                    for (int i = 0; i < count; i++)  // Loop through the data array
                    {
                        if (data[i] == searchValue)  // Check if the number is in the data
                        {
                            found = true;  // Set found to true if the number is found
                            break;  // Exit the loop once the number is found
                        }
                    }
                    if (found)  // If the number is found
                    {
                        Console.WriteLine("The number was found in the data.");  // Inform the user that the number was found
                    }
                    else
                    {
                        Console.WriteLine("The number was not found in the data.");  // Inform the user that the number was not found
                    }
                    break;

                case "4":
                    // View statistics summary
                    if (count > 0)  // Check if there is any data entered
                    {
                        double sum = 0, max = data[0], min = data[0];  // Initialize variables for sum, max, and min
                        for (int i = 0; i < count; i++)  // Loop through the data array
                        {
                            sum += data[i];  // Add the current data point to the sum
                            if (data[i] > max)  // Check if the current data point is greater than the current max
                                max = data[i];  // Update the max value if necessary
                            if (data[i] < min)  // Check if the current data point is less than the current min
                                min = data[i];  // Update the min value if necessary
                        }
                        double average = sum / count;  // Calculate the average

                        Console.WriteLine($"Data count: {count}");  // Display the number of data entries
                        Console.WriteLine($"Sum: {sum}");  // Display the sum of the data
                        Console.WriteLine($"Average: {average:F2}");  // Display the average with 2 decimal places
                        Console.WriteLine($"Maximum: {max}");  // Display the maximum value
                        Console.WriteLine($"Minimum: {min}");  // Display the minimum value
                    }
                    else
                    {
                        Console.WriteLine("No data entered yet.");  // Inform the user if no data was entered
                    }
                    break;

                case "5":
                    // Exit the program
                    running = false;  // Set running to false to exit the loop
                    break;

                default:
                    Console.WriteLine("Invalid option. Please choose a valid option.");  // Handle invalid menu option
                    break;
            }

            Console.WriteLine("\nPress any key to continue...");  // Prompt the user to press a key to continue
            Console.ReadKey();  // Wait for the user to press a key before displaying the menu again
        }
    }
}

 Salida

1. Add new data
2. See all data entered
3. Find an item
4. View statistics summary
5. Exit
Please choose an option (1-5): 1
Enter a number to add: 1
Data added successfully!

Press any key to continue...

 Comparte este Ejercicio C# Sharp

 Más Ejercicios de Programacion C# Sharp de Matrices, Estructuras y Cadenas

¡Explora nuestro conjunto de ejercicios de programación C# Sharp! Estos ejercicios, diseñados específicamente para principiantes, te ayudarán a desarrollar una sólida comprensión de los conceptos básicos de C#. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte de manera gradual a medida que adquieres confianza en la codificación en C#.

  •  Estructura

    En este ejercicio en C#, se te pide crear una estructura (struct) para almacenar los datos de puntos 2D. Los campos de cada punto serán: - Coorde...

  •  Matriz de estructura

    En este ejercicio en C#, se te pide expandir el ejercicio anterior que utilizaba una estructura (struct) para almacenar puntos 2D. Ahora, deberás...

  •  Matriz de estructura y menú

    En este ejercicio en C#, se te pide expandir el ejercicio anterior (arreglo de puntos) para que el programa muestre un menú interactivo. El menú debe pe...

  •  Base de datos de libros

    En este ejercicio en C#, se te pide crear una pequeña base de datos que se usará para almacenar información sobre libros. Cada libro debe almacenar los siguientes dat...

  •  Triángulo V2

    En este ejercicio en C#, se te pide crear un programa que pida al usuario su nombre y luego muestre un triángulo formado por ese nombre, comenzando con 1 letra y aume...

  •  Rectángulo V3

    En este ejercicio en C#, se te pide crear un programa que solicite al usuario su nombre y un tamaño, y luego muestre un rectángulo hueco formado por ese nombre.