find the greatest and lowest number in 2D array

Printable View

• 03-30-2009, 09:53 PM
le_albina@hotmail.com
find the greatest and lowest number in 2D array
Hi,

I'm trying to make a code that calculates and shows the greatest and lowest integer in a 2D array. Here' s what I have so far. I don't know how to continue.
Thanks in advance,
le_albina

public class GreatestLowestRange{
public static void main(String [] args){

int greatest, lowest, range;
int [] [] table = {{10, 12, 14, 16, 18},
{20, 22, 24, 26, 28},
{30, 32, 34, 36, 38},
{40, 42, 44, 46, 48}};
greatest= Greatest(table);

}//End main
//************************************************** *******
private static int Greatest(int tarray[][]){

int i, j, greatest;
greatest=tarray[0][0];
//loop for rows
for (i=0; i<tarray; i++)
{
//loop for columns
for (j=0; j<tarray[i]; j++)
{
if(tarray[i][j]>greatest)
greatest=tarray[i][j];

}//end 1rst for
}//en 2nd for

}//end Greatest

}//end GreatestLowestRange
• 03-30-2009, 11:06 PM
softslate
Looks good but in your for statements you need to compare against the *length* of the array, not the array itself:
Code:

`for (i=0; i<tarray.length; i++)`
and
Code:

`for (j=0; j<tarray[i].length; j++)`
I hope that helps!
• 03-30-2009, 11:09 PM
softslate
Another quick suggestion: As it is you'll have to create a separate method to find the lowest value. But that method will have to go through the same looping as the "greatest" method you have now. You might consider finding both values at the same time in the same method, and have that method return a Map of the two values rather than just one value.