In this post we’ll see a Java program to find maximum and minimum number in a matrix.

#### Java program

Logic for finding the maximum and minimum number in a matrix goes as follows-

Initially assign the element at the index (0, 0) of the matrix to both min and max variables. Then iterate the matrix one row at a time and compare each element with the max variable first, if max variable is less than the current element then assign the current element to the max element else compare current element with the min variable, if min variable is greater than the current element then assign the current element to the min element.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
public class MaxAndMin { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter number of rows and columns in the matrix : "); int row = in.nextInt(); int column = in.nextInt(); // Prepare matrix System.out.print("Enter elements of Matrix : "); int matrix[][] = new int[row][column]; for(int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ matrix[i][j] = in.nextInt(); } } System.out.println("Entered Matrix : " ); for(int i = 0; i < row; i++){ for(int j = 0; j < column; j++){ System.out.print(" " +matrix[i][j]+"\t"); } System.out.println(); } // call method to find min and max in matrix findMinAndMax(matrix); } // Method to find maximum and minimum in matrix private static void findMinAndMax(int[][] matrix){ int maxNum = matrix[0][0]; int minNum = matrix[0][0]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if(maxNum < matrix[i][j]){ maxNum = matrix[i][j]; } else if(minNum > matrix[i][j]){ minNum = matrix[i][j]; } } } System.out.println("Max number: " + maxNum + " Min number: " + minNum); } } |

__Output__

1 2 3 4 5 6 7 |
Enter number of rows and columns in the matrix : 3 3 Enter elements of Matrix : 3 6 12 34 19 5 32 16 7 Entered Matrix : 3 6 12 34 19 5 32 16 7 Max number: 34 Min number: 3 |

That’s all for the topic **Java Program to Find Maximum And Minimum Number in a Matrix**. If something is missing or you have something to share about the topic please write a comment.

**You may also like**