2D Arrays

Detemining the Largest Element in an Array

Page 1 of 1

1 Replies - 587 Views - Last Post: 04 November 2010 - 01:10 AM Rate Topic: -----

#1 Guest_DesmondMpofu*


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  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • 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

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1