In this example I’ll show you how to find out the maximum and minimun values from an 2D int array without Max() and Min() Method.
And You can see the explanation in the following code commets.
C# Console Code:
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 43 44 45 46 47 48 49 50 51 52 53 54 55 | class Program { static void Main(string[] args) { const int x = 3, y = 5; int min, max; int[,] arr = new int[x,y] { { 10,50,13,80,40}, { 1, 250, 65, 28, 15 }, { 12, 17, 45, 20, 6 } }; //Declare two variables max and min to store maximum and minimum. //Assume first array element as maximum and minimum both, say max = arr[0,0] and min = arr[0,0] min = arr[0,0]; max = arr[0,0]; // Iterate through array to find maximum and minimum element in array. //Inside loop for each array element check for maximum and minimum. for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { //Assign current array element to max, if (arr[i,j] > max) if(arr[i,j] > max) { max = arr[i,j]; } //Assign current array element to min if if (arr[i,j] < min) if (arr[i,j] < min) { min = arr[i,j]; } } } //Print Array Elements Console.Write("Array Elements\n"); for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { Console.Write(arr[i, j]+" ,"); } Console.WriteLine(); } Console.WriteLine(); //Print max and min number Console.WriteLine("Maximum element:"+max); Console.WriteLine("Minimum element:" + min); Console.ReadLine(); } } |
Program Output:
Hi,
how would you find out the largest value of a matrix(5 x 5) of type integer holding random values?
Thanks!
https://www.csharp-console-examples.com/csharp-console/find-largest-element-in-a-matrix5x5-in-c/