Group
C# Arrays, Structures and Strings
Objective
1. Ask the user how many numbers they will enter.
2. Reserve space for that many floating-point numbers in an array.
3. Prompt the user to input the numbers and store them in the array.
4. Continuously ask the user for a number and check if it exists in the list.
5. The program should terminate when the user enters "end" instead of a number.
6. The exercise must be done in pairs, but a single source file should be provided, containing both programmers' names in a comment.
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 enter.
- Reserve space for that amount of numbers (floating point).
- Request the data to the user.
- Later, repeat:
* Ask the user for a number (execution ends when he enters "end" instead of a number).
* Say if that number is listed or not.
Must be done in pairs, but you must provide a single source file, containing the names of both programmers in a comment.
Example C# Exercise
Show C# Code
using System;
class Program
{
static void Main()
{
// Programmers: John Doe & Jane Smith
Console.Write("How many numbers will you enter? ");
int count = Convert.ToInt32(Console.ReadLine());
// Create an array to store floating-point numbers
float[] numbers = new float[count];
// Request numbers from the user
Console.WriteLine("Enter the numbers:");
for (int i = 0; i < count; i++)
{
Console.Write($"Number {i + 1}: ");
numbers[i] = Convert.ToSingle(Console.ReadLine());
}
// Search loop
while (true)
{
Console.Write("\nEnter a number to check (or type 'end' to exit): ");
string input = Console.ReadLine();
if (input.ToLower() == "end")
break;
if (float.TryParse(input, out float searchNumber))
{
// Check if the number exists in the array
bool found = false;
foreach (float num in numbers)
{
if (num == searchNumber)
{
found = true;
break;
}
}
if (found)
Console.WriteLine("The number is in the list.");
else
Console.WriteLine("The number is NOT in the list.");
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
}
Console.WriteLine("Program ended.");
}
}
Output
How many numbers will you enter? 3
Enter the numbers:
Number 1: 5.5
Number 2: 3.2
Number 3: 8.1
Enter a number to check (or type 'end' to exit): 3.2
The number is in the list.
Enter a number to check (or type 'end' to exit): 7.0
The number is NOT in the list.
Enter a number to check (or type 'end' to exit): end
Program ended.