Grupo
Gestión Dinámica de Memoria en C#
Objectivo
1. Solicitar continuamente al usuario un número o un comando.
2. Si el usuario introduce un número, almacenarlo en una lista.
3. Si el usuario introduce "suma", mostrar la suma de todos los números introducidos hasta el momento.
4. Si el usuario introduce "ver", mostrar todos los números introducidos.
5. Si el usuario introduce "fin", finalizar el programa.
6. Asegurarse de que el programa pueda gestionar correctamente tanto números como comandos.
Crear un programa que permita al usuario introducir una cantidad ilimitada de números. También se pueden introducir los siguientes comandos:
- "suma", para mostrar la suma de todos los números introducidos hasta el momento.
- "ver", para mostrar todos los números introducidos.
- "fin", para salir del programa.
Este es un ejemplo de ejecución:
¿Número o comando? 5
¿Número o comando? 3
¿Número o comando? Ver
Números ingresados:
5
3
¿Número o comando? 6
¿Número o comando? Suma
Suma = 14
¿Número o comando? -7
¿Número o comando? Fin
Ejemplo de ejercicio en C#
Mostrar código C#
using System;
using System.Collections.Generic; // Import the namespace for list management
class Program
{
static void Main()
{
List numbers = new List(); // Create a list to store entered numbers
string input; // Variable to store user input
while (true) // Infinite loop to keep asking for input
{
Console.Write("Number or command? "); // Prompt the user for input
input = Console.ReadLine(); // Read user input
if (input == "end") // Check if the user wants to exit
{
break; // Exit the loop and terminate the program
}
else if (input == "sum") // Check if the user wants to sum all numbers
{
int sum = 0; // Initialize sum variable
foreach (int num in numbers) // Iterate through the list
{
sum += num; // Add each number to the sum
}
Console.WriteLine("Sum = " + sum); // Display the sum
}
else if (input == "view") // Check if the user wants to view entered numbers
{
Console.WriteLine("\nEntered numbers:"); // Display heading
foreach (int num in numbers) // Iterate through the list
{
Console.WriteLine(num); // Print each number
}
Console.WriteLine(); // Print an empty line for readability
}
else // Assume the input is a number
{
if (int.TryParse(input, out int number)) // Try to convert input to an integer
{
numbers.Add(number); // Add the number to the list
}
else // If input is not a valid number or command
{
Console.WriteLine("Invalid input. Please enter a number or a valid command.");
}
}
}
}
}
Output
Number or command? 5
Number or command? 3
Number or command? view
Entered numbers:
5
3
Number or command? 6
Number or command? sum
Sum = 14
Number or command? -7
Number or command? end
Código de ejemplo copiado
Comparte este ejercicio de C#