June 23, 2022

Java Program to Find Maximum And Minimum Number in a Matrix

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

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 variable, 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.

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
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

No comments:

Post a Comment