Loading ...

How can we find highest second and lowest second number in a particular array? | CodeAsp.Net

How can we find highest second and lowest second number in a particular array?

 /5
0 (0votes)

Yesterday, I was sitting with my college friends at a coffee shop. One of my friends asked me a question that how we can find highest second and lowest second number in a particular array, and without the help of any function like orderBy. So, I took a notebook and solved his question. Now I am writing a blog on that logic as I want to share my logic with everybody.

Here is my code:-

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class secondHighestLowest : System.Web.UI.Page
{
// this is an array.
int[] arr = new int[10] { 45, 3, 64, 6, 24, 75, 3, 6, 24, 45 };

protected void Page_Load(object sender, EventArgs e)
{
// calling second highest number method.
secondHighestNumber();

// calling second lowest number method.
secoundLowestNumber();
}

/// <summary>
/// In this function I will get second highest number.
/// </summary>
private void secondHighestNumber()
{
int firstHighestNumber = arr[0];
int secondHighestNumber = arr[0];

// first I am getting highest number of array.
for(int i = 0; i<arr.Length; i++)
{
if (arr[i]>firstHighestNumber)
{
firstHighestNumber = arr[i];
}
}

// when I got highest number of array, then I will check the second highest number of array.
// in if condition I am getting second highest number of array which is not equal to first
// highest number.
for (int x = 0; x < arr.Length; x++)
{
if (arr[x]>secondHighestNumber && firstHighestNumber!=arr[x])
{
secondHighestNumber = arr[x];
}
}

// showing second highest number.
Response.Write("secondHighestNumber---- " + secondHighestNumber + "</br>");

}

/// <summary>
/// In this function I will get second lowest number.
/// </summary>
private void secoundLowestNumber()
{
int firstLowestNumber = arr[0];
int secondLowestNumber = arr[0];

// first I am getting lowest number of array.
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < firstLowestNumber)
{
firstLowestNumber = arr[i];
}
}

// when I got lowest number of array, then I will check the lowest highest number of array.
// in if condition I am getting second lowest number of array which is not equal to first
// lowest number.
for (int x = 0; x < arr.Length; x++)
{
if (arr[x] < secondLowestNumber && firstLowestNumber != arr[x])
{
secondLowestNumber = arr[x];
}
}
// showing second lowest number.
Response.Write("secondLowestNumber---- " + secondLowestNumber + "</br>");
}
}

Cheers!!
Happy coding:)

Comments (no comments yet)

Top Posts