Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum and maximum number from array, minimum is always 0

Tags:

c#

The program first asks the user for the number of elements to be stored in the array, then asks for the numbers.

This is my code

    static void Main(string[] args)
    {
        Console.Write("How many numbers do you want to store in array: ");
        int n = Convert.ToInt32(Console.ReadLine());
        int[] numbers = new int[n];
        int min = numbers[0];
        int max = numbers[0];

        for (int i = 0; i < n; i++)
        {
            Console.Write("Enter number {0}:  ", i+1);
            numbers[i] = Convert.ToInt32(Console.ReadLine());
        }

        for (int i = 0; i < n; i++)
        {
            if (min > numbers[i]) min = numbers[i];
            if (max < numbers[i]) max = numbers[i];
        }
        Console.WriteLine("The minimum is: {0}", min);
        Console.WriteLine("The maximum is: {0}", max);
        Console.ReadKey();
    }
  }
}

But minimum value is always 0, why is that?

like image 716
alex Avatar asked Nov 16 '13 15:11

alex


People also ask

How do you find the maximum and minimum value of an array?

The function getresult( int arr[],int n) is to find the maximum and minimum element present in the array in minimum no. of comparisons. If there is only one element then we will initialize the variables max and min with arr[0] . For more than one element, we will initialize max with arr[1] and min with arr[0].

Can 0 be a minimum value?

Normally, zero value is supposed to be the minimum value among positive numbers. But in some cases, you need to find the minimum value in a range excluding the zero value.

What is the complexity of finding maximum and minimum value from an array of n values?

Return max and min. Time Complexity is O(n) and Space Complexity is O(1). For each pair, there are a total of three comparisons, first among the elements of the pair and the other two with min and max.


1 Answers

Besides on your problem, you can use Enumerable.Min and Enumerable.Max methods like;

int[] numbers = new int[]{1, 2, 3 ,4};
Console.WriteLine(numbers.Min()); //1
Console.WriteLine(numbers.Max()); //4

Don't forget to add System.Linq namespace.

like image 197
Soner Gönül Avatar answered Oct 19 '22 04:10

Soner Gönül