Friday, January 15, 2021

Q.13: How to find third largest integer in an array using only one loop?

 Ans.: The user will input an unsorted integer array and the method should find the third largest integer in the array.

  • input: 3 2 1 5 4, output: 3
internal static void FindthirdLargeInArray(int[] arr)
{
int max1 = int.MinValue;
int max2 = int.MinValue;
int max3 = int.MinValue;
foreach (int i in arr)
{
if (i > max1)
{
max3 = max2;
max2 = max1;
max1 = i;
}
else if (i > max2 && i != max1)
{
max3 = max2;
max2 = i;
}
else if (i > max3 && i != max2 && i != max1)
{
max3 = i;
}
}
Console.WriteLine(max3); ;
}

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...