In this example, i’ll show you How to Find 2nd Maximum Number in an array in C#.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public static void Main() { int[] ar = { 31, -41, 26, 59, -53, 58, 97, -93, -23, 84 }; int max1 = 0, max2 = 0; for (int i = 0; i < ar.Length; i++) { if (ar[i] > max1 && max2 <=max1) { max2 = max1; max1 = ar[i]; } else if(ar[i]>max2) { max2 = ar[i]; } } Console.WriteLine(“First Max : {0} and Second max in array : {1} in array”, max1, max2); } |
Output: