C# How To Find Min and Max in an Array
Min and Max in Array
Use the Min() and Max() methods from the System.Linq namespace:
Example
int[] numbers = {45, 12, 85, 32, 89, 39};
Console.WriteLine("Min: " + numbers.Min());
Console.WriteLine("Max: " + numbers.Max());
You can also find them with a loop:
Example
int[] numbers = {45, 12, 85, 32, 89, 39};
int min = numbers[0];
int max = numbers[0];
foreach (int num in numbers)
{
if (num < min)
{
min = num;
}
if (num > max)
{
max = num;
}
}
Console.WriteLine("Min: " + min);
Console.WriteLine("Max: " + max);
Explanation:Min() returns the lowest value, and Max() returns the highest value.
The loop starts with the first element as both min and max, and updates them each time it finds a lower or a higher value.
Related Pages
C# Loop Through Arrays Tutorial