public int FindlargestNumber(int[] iarray)
{
int maxvalue = 0;
for (int i = 0; i <= iarray.Length - 1; i++)
{
if (iarray[i] > maxvalue)
{
maxvalue = iarray[i];
}
if (maxvalue % 2 == 0)
{
}
}
return maxvalue;
}
This will return only one max value how would I implement the same to get top n values??
Regards
Sangeetha
AlanPosted Nov 4, 2008, 11:23 AM
Incidentally, if you'd prefer to do this without sorting the array, then you could use the technique I suggested in your other thread:
http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=49744
The code for that would be:
public int FindLargestEvenProduct(int[] iarray, int len)
{
if (len == 0 || len != iarray.Length) return -1;
ArrayList list = new ArrayList(iarray);
int[] maxEven = new int[2]{-1, -1};
for (int iter = 0; iter < 2; iter++)
{
int pos = -1;
for (int i = 0; i < list.Count; i++)
{
if (((int)list[i] % 2) == 0)
{
if (maxEven[iter] == -1 || ((int)list[i] > maxEven[iter]))
{
maxEven[iter] = (int)list[i];
pos = i;
}
}
}
if (maxEven[iter] == -1) return -1;
list.RemoveAt(pos);
}
return maxEven[0] * maxEven[1];
}
AlanPosted Nov 4, 2008, 5:26 AM
It seems strange that the question is asking you to input the length of the array into the method when this can easily be found from the array's Length property. Are you sure that this is an exercise in C# and not C programming?
Anyway, to find the largest two even numbers (or, for that matter, the largest 'n' numbers), I would suggest that you sort the array and then iterate through it backwards to get the largest numbers. If the data is inconsistent or there aren't at least two even numbers in the array, then you'll need some way of indicating this to the caller. Rather than throwing an exception, I've returned the 'impossible' value of -1 in the following code:
public int FindLargestEvenProduct(int[] iarray, int len)
{
// check for empty array or inconsistent length
if (len == 0 || len != iarray.Length) return -1;
// clone array so as not to change original
int[] clone = (int[])iarray.Clone();
// sort the clone into numeric order
Array.Sort(clone);
// declare variables to hold two largest even numbers
int maxEven1 = -1;
int maxEven2 = -1;
// iterate backwards through clone to find two largest
for (int i = len - 1; i >= 0; i--)
{
if ((clone[i] % 2) == 0)
{
if (maxEven1 == -1)
{
maxEven1 = clone[i];
}
else
{
maxEven2 = clone[i]; // no need to check any more numners
break;
}
}
}
// if maxEven2 is still -1, there must be fewer than
// two even numbers in the array
if (maxEven2 == -1) return -1;
// return product
return maxEven1 * maxEven2;
}