Odie Odie - 2 years ago 136
C# Question

Get the lowest value on a List<> array

int numbers;
List<int> arrayInt = new List<int>();

for (int i = 0; i <= 10; i++)
{
Console.Write("Enter 10 integers: ");
numbers = Int32.Parse(Console.ReadLine());
arrayInt.Add(i);

if (i == 10)
{
int[] output = arrayInt.ToArray();
int min = output.Min();
Console.WriteLine(min); //outputs 0
}
}


The user enters 10 integers and adds it into the
arrayInt
list.

After the user enters 10 integers, the second
if
gets the lowest integer by converting my
arrayInt
list to an array. I used the
.Min()
to get the lowest int but it still outputs
0
.

What's wrong in my code?

For ex.,
I enter 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
then the
Console.WriteLine(min)
should output
1
because it's the lowest integer.

Answer Source

I would suggest a couple of changes:

  1. As others have said, you're adding the counter variable to the list rather than the user input. That is easily fixed.
  2. You have additional logic inside your loop to do something different when you reach the last index. Instead of this, you should just modify your loop condition so that it exits at the appropriate time, then do your final steps after the loop has completed. This way, the only job of the loop is to gather user input.
  3. You should use Int.TryParse instead of Parse, because it will return false if the user gives invalid input, in which case we can just tell them to try again.
  4. You don't need to convert the List to an Array. There is an extension method for Lists that will give you the minimum value. You just need using System.Linq at the top of your file to use it.

Here's the code:

static void Main()
{
    var allNumbers = new List<int>();

    for (int i = 0; i < 10; i++)
    {
        Console.Write($"Enter integer #{i + 1}: ");

        int input;
        while (!int.TryParse(Console.ReadLine(), out input))
        {
            Console.Write(" - Invalid input, try again: ");
        }

        allNumbers.Add(input);
    }

    Console.WriteLine($"\nThank you! The smallest number you entered is: {allNumbers.Min()}");

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download