In this example, i’ll show you How to Find 3rd 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 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 |
// C# code to find largest // three elements in an array using System; class PrintLargest { // Function to print three // largest elements static void print3largest(int[] arr, int arr_size) { int i, first, second, third; // There should be atleast three elements if (arr_size < 3) { Console.WriteLine("Invalid Input"); return; } third = first = second = 000; for (i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second) { third = second; second = arr[i]; } else if (arr[i] > third) third = arr[i]; } Console.WriteLine("Three largest elements are " + first + " " + second + " " + third); } // Driver code public static void Main() { int[] arr = new int[] { 12, 13, 1, 10, 34, 1 }; int n = arr.Length; print3largest(arr, n); } } |
Output: