Java program to display largest element in each row in 2-D Array

Display Largest Element in 2-D Array

In this article, we will discuss about largest element in each row in 2-D Array. Array has n-rows and m-columns , here our task is to write a program to Display the largest element in each row in a 2-D Array in Java.

• Sample input: a=[[1,2,3],[6,5,4],[8,9,7]]
• Sample output: 3 6 9

Approach

• Take the row and column of a matrix as input.
• Take  row*column space separated elements as input.
• Declare max variable and initialize it with the Minimum value of Integer.
• Traverse each element of a row and print it.
• At the end all the max element of each row get printed.

Code in Java

`import java.util.*;class Solution{     public static void main(String[] args)     {           Scanner sc=new Scanner(System.in);           System.out.println("Enter the number of rows");           int row=sc.nextInt();           System.out.println("Enter the number of columns");           int col=sc.nextInt();           int matrix[][]=new int[row][col];           System.out.println("Enter the elements of matrix");           for(int i=0;i<row;i++)              for(int j=0;j<col;j++)                  matrix[i][j]=sc.nextInt();           int max=Integer.MIN_VALUE;                       System.out.println("Max Value of each row");           for(int i=0;i<row;i++)           {                    max=Integer.MIN_VALUE;                    for(int j=0;j<col;j++)                        max=Math.max(max,matrix[i][j]);                    System.out.print(max+" ");            }        }}`

Output :

`Enter the number of rows3Enter the number of columns3Enter the elements of matrix1 2 36 5 48 9 7Max Value of each row3 6 9`