Maximum and third maximum value in an array C#
I have one predefined array and want to sort out maximum value and third maximum value from it. Generally we can do it by using .NET predefined functions or without predefined functions.
Let me say, I have one array and I want to get the greatest number and 3rd greatest number from it.
3rd Maximum Value.
I am listing out the simple steps to do this task easily understanble.
1) Define the array int[] myArray = { 19, 3, 34, 15, 13, 0, 29, 39 };
2) Initialize the variables int s = 0, l = 0, m = 0;
3) Looping it from 0 to array length.
4) Performing the if condition with l < myArray[loop] && m <= l.
5) Assigning m in s , m in l and myArray[loop] in l.
6) Getting the output from s.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is a Program to get the 3rd Maximum value from a given Array");
Console.WriteLine("******************************************************************");
Console.WriteLine();
int s = 0, l = 0, m = 0;
int[] myArray = { 19, 3, 34, 15, 13, 0, 29, 39 };
for (int loop = 0; loop < myArray.Length; loop++)
{
if (l < myArray[loop] && m <= l)
{
s = m;
m = l;
l = myArray[loop];
}
else if (m < myArray[loop] && s <= m)
{
s = m;
m = myArray[loop];
}
else if (s <= myArray[loop])
{
s = myArray[loop];
}
}
Console.WriteLine(s.ToString());
Console.Read();
}
}
}
Maximum Value:
I am listing out the simple steps to do this task easily understanble.
7) Define the array int[] myArray = { 21, -31, 36, 99, -33, 58, 87, -83, -73, 94 };
8) Initialize the variables int maxNum1 = 0, maxNum2 = 0;
9) Looping it from 0 to array length
10)Performing the if condition with myArray[loop] > maxNum1 && maxNum2 <= maxNum1.
11)Assigning maxNum1 in maxNum2 and myArray[loop] in maxNum1.
12)Else condition for the if with myArray[loop] > maxNum2 and Assigning myArray[loop] in maxNum1.
13)Getting the output from maxNum1 and maxNum2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This is a Program to get the Maximum value and Second Maximum value from a given Array");
Console.WriteLine("******************************************************************");
Console.WriteLine();
int[] myArray = { 21, -31, 36, 99, -33, 58, 87, -83, -73, 94 };
int maxNum1 = 0, maxNum2 = 0;
for (int loop = 0; loop < myArray.Length; loop++)
{
if (myArray[loop] > maxNum1 && maxNum2 <= maxNum1)
{
maxNum2 = maxNum1;
maxNum1 = myArray[loop];
}
else if (myArray[loop] > maxNum2)
{
maxNum2 = myArray[loop];
}
}
Console.WriteLine("First Max : {0} and Second max in array : {1} in a given array", maxNum1, maxNum2);
Console.Read();
}
}
}