Sample 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 | using System; using System.Linq; namespace Logical_Programs { class _2ndLargestNumberInArray { static void Main() { int[] myArray = new int[] { 0, 48, 65, 10, 49, 3, 40 }; Console.WriteLine("find 2nd height number in array"); Console.WriteLine("**********************************"); Console.WriteLine("First Approach: Using Foreach"); Console.WriteLine("Result: {0}", get2ndHeightNumber_FirstApproach(myArray)); Console.WriteLine("Second Approach: Using Linq Query"); Console.WriteLine("Result: {0}", get2ndHeightNumber_SecondApproach(myArray)); Console.WriteLine("**********************************"); Console.WriteLine("Press any key to continue..."); Console.ReadLine(); } /// <summary> /// get 2nd height number with help of foreach /// </summary> /// <param name="myArray"></param> /// <returns></returns> public static int get2ndHeightNumber_FirstApproach(int[] myArray) { int largest = int.MinValue; int second = int.MinValue; foreach (int i in myArray) { if (i > largest) { second = largest; largest = i; } else if(i > second) { second = i; } } return second; } /// <summary> /// get 2nd height number with help of linq query /// </summary> /// <param name="myArray"></param> /// <returns></returns> public static int get2ndHeightNumber_SecondApproach(int[] myArray) { int secondHighest = myArray.OrderByDescending(x => x).Distinct().Skip(1).First(); return secondHighest; } } } |
Output:
If you like this post. Kindly share your feedback.
No comments:
Post a Comment