I'm trying to create a program that inputs a succession of numbers until '-1' is entered. Then, the program will output the highest and lowest of the numbers entered. Here is what I've got:
int[] numbers = new int[]; // Creating a blank array.
int number, max, min;
Console.Write("Enter a number: ");
number = Convert.ToInt32(Console.ReadLine());
while (number != -1)
{
// This line would append user input to the array.
Console.Write("Enter another number (Enter -1 to stop): ");
number = Convert.ToInt32(Console.ReadLine());
}
max = numbers[0];
min = numbers[0];
for (int i = 1; i < numbers.Length; i )
{
if (numbers[i] > max)
{
max = numbers[i];
}
if (numbers[i] < min)
{
min = numbers[i];
}
}
Console.Write("The largest number you entered was: {0}, and the smallest number you entered was: {1}.", max, min);
CodePudding user response:
Since you don't know the count of numbers user will be entering you shouldn't be using arrays
, instead I suggest using List
as lists support far more operations like add
or remove
CodePudding user response:
I think this will help you:
private const int EndOfInput = -1;
private static void Main(string[] args)
{
int currentInput;
var allInput = new List<int>();
do
{
Console.Write("Enter another number (Enter -1 to stop): ");
if (int.TryParse(Console.ReadLine(), out currentInput)
&& currentInput != EndOfInput)
{
allInput.Add(currentInput);
}
} while (currentInput != EndOfInput);
if (allInput.Count != 0)
Console.Write($"The largest number you entered was: {allInput.Max()}, and the smallest number you entered was: {allInput.Min()}.");
else
Console.WriteLine("You haven't entered any numbers.");
}
Please note that it's better to use variable-size collections like List<T>
instead of regular arrays if the size of the input is unknown at runtime.