I am learning how to create simple .NET applications. In this application I'm adding numbers in array of integers from TextBox
, and display the biggest and smallest number from this array in the ListBox
. The problem is that when I'm finding minimum number using Min
method it always gives me 0, however Max
method works just fine
public partial class Form1 : Form
{
// ...
int[] array = new int[100];
int counter = 0;
private void button1_Click_1(object sender, EventArgs e)
{
for (int i = 0; i <= counter; i++)
{
array[i] = Convert.ToInt32(txtInsertNumber.Text);
}
counter++;
}
private void btnShowMinMax_Click_1(object sender, EventArgs e)
{
listBox1.Items.Clear();
int max = array.Max();
int min = array.Min();
int maxIndex = Array.IndexOf(array, max);
int minIndex = Array.IndexOf(array, min);
listBox1.Items.Add(array[maxIndex] + " " + array[minIndex]);
}
}
Your array int[] array = new int[100];
is initialized with 100 integers with the default value of 0. That's why the minimum value is 0.
The solution would be to have an array of Nullable<int>
to differenciate "no value" null
from real values. Example:
int[] a = new int[50];
Console.WriteLine(a.Min()); // prints "0"
Nullable<int>[] b = new Nullable<int>[100];
Console.WriteLine(b.Min()); // prints ""