Find minimum and maximum number from an array in C#
This post will discuss how to find the minimum and maximum number from an array in C#.
1. Using Linq
A simple solution to find the minimum and maximum value in a sequence of values is using the Enumerable.Min and Enumerable.Max methods from the System.Linq namespace.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 8, 3, 5, -1, 2 }; Console.WriteLine("Minimum number is " + arr.Min()); Console.WriteLine("Maximum number is " + arr.Max()); } } |
Output:
Minimum number is -1
Maximum number is 8
2. Using Array.Sort() Method
Another plausible, but less recommended way to find the minimum/maximum of an array is to sort the array in ascending order. Then the first and last element of the sorted array would the minimum and the maximum element, respectively.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { int[] arr = { 8, 3, 5, -1, 2 }; Array.Sort(arr); if (arr.Length > 0) { Console.WriteLine("Minimum number is " + arr[0]); Console.WriteLine("Maximum number is " + arr[arr.Length - 1]); } } } |
Output:
Minimum number is -1
Maximum number is 8
3. Using Custom Routine
Finally, we can write a custom routine for finding the minimum and the maximum number of an array. The idea is to traverse the array and keep track of the minimum or maximum value found so far. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System; public class Example { public static int findMin(int[] arr) { if (arr.Length == 0) { throw new Exception("Array is empty"); } int min = int.MaxValue; foreach (var i in arr) { if (i < min) { min= i; } } return min; } public static int findMax(int[] arr) { if (arr.Length == 0) { throw new Exception("Array is empty"); } int max = int.MinValue; foreach (var i in arr) { if (i > max) { max = i; } } return max; } public static void Main() { int[] arr = { 8, 3, 5, -1, 2 }; Console.WriteLine("Minimum number is " + findMin(arr)); Console.WriteLine("Maximum number is " + findMax(arr)); } } |
Output:
Minimum number is -1
Maximum number is 8
That’s all about finding the minimum and maximum number from an array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)