Ejercicio
Buscar en matriz
Objetivo
Cree un programa en C# que diga si un dato pertenece a una lista que se creó anteriormente.Los pasos a seguir son:
- Preguntar al usuario cuántos datos introducirá.
- Reservar espacio para esa cantidad de números (coma flotante).
- Solicitar los datos al usuario
- Más tarde, repite:
* Pida al usuario un número (la ejecución termina cuando ingresa "fin" en lugar de un número).
* Diga si ese número aparece o no.
Debe hacerse en parejas. pero debe proporcionar un único archivo de origen que contenga los nombres de ambos programadores en un comentario.
Código de Ejemplo
using System; // Import the System namespace for basic functionality
class Program // Define the main class
{
static void Main() // The entry point of the program
{
// Comment with the names of both programmers
// Programmers: [Your Name] & [Partner's Name]
// Ask the user how many data points they want to enter
Console.Write("How many numbers will you enter? ");
int count = Convert.ToInt32(Console.ReadLine()); // Read and store the number of data points
// Create an array to store the floating point numbers
double[] numbers = new double[count];
// Ask the user for the data and store it in the array
Console.WriteLine("Enter the numbers:");
for (int i = 0; i < count; i++)
{
Console.Write($"Enter number {i + 1}: "); // Prompt the user for a number
numbers[i] = Convert.ToDouble(Console.ReadLine()); // Convert the input to a double and store it in the array
}
// Start checking if the entered numbers exist in the list
while (true)
{
Console.Write("\nEnter a number to search for (or 'end' to quit): ");
string input = Console.ReadLine(); // Read user input
// Check if the user wants to end the program
if (input.ToLower() == "end")
{
break; // Exit the loop if the user types "end"
}
// Convert the input to a double and check if it exists in the array
double searchValue;
bool isValid = double.TryParse(input, out searchValue); // Check if the input can be parsed as a double
if (isValid)
{
// Check if the number exists in the array
bool found = false;
foreach (double number in numbers)
{
if (number == searchValue)
{
found = true;
break;
}
}
// Display whether the number is found in the array or not
if (found)
{
Console.WriteLine($"The number {searchValue} is in the list.");
}
else
{
Console.WriteLine($"The number {searchValue} is not in the list.");
}
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number or 'end' to quit.");
}
}
Console.WriteLine("Goodbye!");
}
}