Riza Mk Riza Mk - 2 months ago 20
C# Question

max and min of array c#

So, I am entering double values into array, then founding sum(without max and min), average, max and min. Everything is ok, but min is permanently 0, and I don't know what to do;

NOTE: no use of

Max()
and
Min()
methods

static void Main(string[] args)
{
double avr = 0;
double sum = 0;
double max;
double min;
Console.WriteLine("how many numbers?");
int b = Convert.ToInt32(Console.ReadLine());
double[] arr = new double[b];
max = arr[0];
min = arr[0];
for (int i = 0; i < b; i++)
{
arr[i] = Convert.ToDouble(Console.ReadLine());
if (arr[i] >= max)
{
max = arr[i];
}

else if (arr[i] <= min)
{
min = arr[i];
}
sum += arr[i];
}

sum = sum - max - min;
avr = sum / (b - 2);

Console.WriteLine("sum = {0},average = {1}, max = {2}, min = {3}", sum, avr, max, min);
Console.ReadKey();
}

Answer

You use default values of double to initialize min and max - so both will be set to 0 prior any iteration. So min will work incorrectly if all elements greater than zero, max - when all elements less than zero.

Fix

  • use double.MinValue / double.MaxValue to corresponding min/max so any actual value will satisfy if condition max = double.MinValue;
  • better yet split reading of array and computing statistics - than using arr[0] will actually contain valid user provided value instead of default.