Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

how to find the largest number in a 2d array java

// Assume the 2D array is holding int values
// Method for finding largest number in array given below
// if 2D array is null or empty, return min int value

public int findLargest(int[][] mat) {
	int max = Integer.MIN_VALUE; // running max value
  	if(mat == null || mat.length == 0) {
     	return max; // return min int if mat is null or empty 
    }
  
  	final int ROW = mat.length; // nb of rows in 2D array
  	final int COL = mat[0].length; // nb of cols in 2D array
  	// Iterate over elements to find largest value
  	for(int row=0; row < ROW; row++) {
    	for(int col=0; col < COL; col++) {
        	if(mat[row][col] > max) {
            	max = mat[row][col]; // update running max if larger val is found 
            }
        }
    }
	
  	return max;
}
 
PREVIOUS NEXT
Tagged: #find #largest #number #array #java
ADD COMMENT
Topic
Name
1+6 =