This post is about writing a Java program to find the maximum and minimum numbers in a given matrix (2D Array).
Solution to Find largest and smallest number in a matrix
Logic here is to have two variables for maximum and minimum numbers, initially assign the element at the first index of the matrix to both the variables.
Then iterate the matrix one row at a time and compare each column element with the max number if max number is less than the column element then assign column element to the max number.
If max number is greater than the column element then check if minimum number is greater than the column element, if yes then assign column element to the minimum number.
Java program to find largest and smallest number in a matrix
In the first part of the program matrix elements are entered and the end matrix is displayed then the maximum and minimum numbers are found using the above mentioned logic.
public class MatrixMinMax { public static void main(String[] args) { int rows; int columns; Scanner scanner = new Scanner (System.in); // System.out.println("Enter number of rows: "); rows = scanner.nextInt(); System.out.println("Enter number of columns: "); columns = scanner.nextInt(); int[][] matrix = new int [rows][columns]; System.out.println("Enter matrix numbers: "); for (int i = 0; i < rows; i++) { System.out.println("Enter numbers for row - " + (i+1) + " and press enter"); for (int j = 0; j < columns; j++) { matrix[i][j] = scanner.nextInt(); } } scanner.close(); // Displaying entered matrix System.out.println("Matrix as entered"); for (int i = 0; i < matrix .length; i++) { System.out.println(); for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } } System.out.println(); findMinMax(matrix); } // Method to find max and min private static void findMinMax(int[][] matrix){ // start by assigning the first matrix element // to both the variables 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("Largest number: " + maxNum + " Smallest number: " + minNum); } }
Output
Enter number of rows: 3 Enter number of columns: 3 Enter matrix numbers: Enter numbers for row - 1 and press enter 2 5 8 Enter numbers for row - 2 and press enter 17 4 9 Enter numbers for row - 3 and press enter 22 34 3 Matrix as entered 2 5 8 17 4 9 22 34 3 Largest number: 34 Smallest number: 2
That's all for this topic Find Maximum And Minimum Numbers in a Given Matrix Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-