Page 1 of 1

Reputation:

2D Arrays

Posted 04 November 2010 - 12:32 AM

Hi

Please help me with the code below, it is supposed to print the largest array element amongst all the elements initialized. It is not doing that instead, it displays the largest element in the last row. I can't figure out what is wrong

```import java.io.* ;
class ArrayMaximum
{
public static void main ( String[] args ) throws IOException
{
int data2[][] = new int[][] {{3, 90, 5, 8, 1},
{1, 4, 4, 129, 13, 12, 58, 77, 12},
{9, 1, 13},
{0, 2,0,50, 75, 77, 3, -1 }};
int sum =0;
int max = data2[0][0];
for ( int row=0; row < data2.length; row++)
{
for ( int col=0; col < data2[row].length-1; col++)
{
if (data2[row][col+1]>data2[row][col])
max = data2[row][col+1];
}
}
System.out.println(  max);
}
}

```

Is This A Good Question/Topic? 0

Replies To: 2D Arrays

#2 DJPlayer

Reputation: 14
• Posts: 73
• Joined: 19-September 07

Re: 2D Arrays

Posted 04 November 2010 - 01:10 AM

```public static void main ( String[] args ) throws IOException
{
int data2[][] = new int[][]
{{3, 90, 5, 8, 1},
{1, 4, 4, 129, 13, 12, 58, 77, 12},
{9, 1, 13},
{0, 2,0,50, 75, 77, 3, -1 }};

int max = data2[0][0];
for (int row=0; row < data2.length; row++)
{
for ( int col=0; col < data2[row].length; col++)
{
System.out.println("data at row " +row+", col "+col+ " = "+data2[row][col]);
if (max < data2[row][col])
max = data2[row][col];

}
}
System.out.println("max = " +max);
}
}

```

the for loop is doing all the work for you.. you don't need to try and change positions within the if statement.

get way to check is println on the rows, cols to make sure you hit them all (which you weren't)
then println on the array values to make sure you compare all your values.
then a simple if statement to compare your current largest to the new 2d array value.

This post has been edited by DJPlayer: 04 November 2010 - 01:17 AM

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }