June 23, 2022

Java Program to Find The Maximum Element in Each Row of a Matrix

In this post we’ll see a Java program to find the maximum element in each row of a matrix.

For example if there is a matrix as given below-

10  8   6
0   13  7
17  3   15

Then program should find the maximum element for each row in the matrix as follows-

Maximum element in row-1 = 10

Maximum element in row-2 = 13

Maximum element in row-3 = 17

Java program - Finding max element in each row of a matrix

public class MatrixMaxElement {

  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 col = in.nextInt();
    // Prepare matrix
    int[][] matrix = prepareMatrix(row, col);
    findMaxInEachRow(matrix);
    in.close();
  }
  // Method to enter matrix elements
  private static int[][] prepareMatrix(int row, int column){
    Scanner sc = new Scanner(System.in);
    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] = sc.nextInt();
      }
    }
    sc.close();
    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();
    }
    return matrix;
  }
  // Method to find the maximum element in each row
  private static void findMaxInEachRow(int[][] matrix){
    int[] tempArray = new int[matrix.length];
    for (int i = 0; i < matrix.length; i++) {
      // Start with first element of the row
      int max = matrix[i][0];
      for (int j = 0; j < matrix[i].length; j++) {
        if(max < matrix[i][j]){
          max = matrix[i][j];
        }
        tempArray[i] = max;
      }         
    }        
    // Displaying max elements
    for (int i = 0; i < tempArray.length; i++) {
      System.out.println("Maximum element in row-" + (i + 1) + " = " + tempArray[i]);
    }
  }
}
Output
Enter number of rows and columns in the matrix: 3 3
Enter elements of Matrix : 10 8 6
0 13 7
17 3 15
Entered Matrix : 
 10	 8	 6	
 0	 13	 7	
 17	 3	 15	
Maximum element in row-1 = 10
Maximum element in row-2 = 13
Maximum element in row-3 = 17

That's all for the topic Java Program to Find The Maximum Element in Each Row of 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