In: Computer Science
Write a method with the following header to return an
array of integer values which are the largest values from each row
of a 2D array of integer values
public static int[] largestValues(int[][] num)
For example, if the 2D array passed to the method is:
8 5 5 6 6
3 6 5 4 5
2 5 4 5 2
8 8 5 1 6
The method returns an array of integers which are the largest
values from each row as follows:
8
6
5
8
In the main method, create a 2D array of integer values with the
array size 4 by 5 and invoke the method to find and display the
largest values from each row of the 2D array.
You can generate the values of the 2D array using the Math.random()
method with the range from 0 to 9.
JAVA CODE :
import java.util.*;
import java.lang.*;
public class Main
{
public static int[] largestValues(int[][] num)
{
int max = -1;
int result[] = new int[num.length];
for(int i = 0; i < num.length; i++) // ioterate through each
row
{
for(int j = 0; j < num[i].length; j++)
{
if(num[i][j] > max) // find maximum element
{
max = num[i][j];
}
}
result[i] = max; // store them in the 1D array
max = -1;
}
return result; // return the result
}
public static void main(String[] args) {
Scanner s = new
Scanner(System.in);
int row = 4;
int column = 5;
int a[][] = new
int[row][column];
for(int i = 0; i < row;
i++){
for(int j = 0; j < column;
j++){
a[i][j] = (int)(Math.random() *
10); // generate random integers
}
}
int result[] =
largestValues(a);
System.out.println("2D array with
generated random numbers are : ");
for(int i = 0; i < row;
i++){
for(int j = 0; j < column;
j++){
System.out.print(a[i][j] + " "); //
print the 2D array
}
System.out.println();
}
System.out.println("Largest element
in each row is : ");
for(int i = 0; i < row;
i++)
{
System.out.println(result[i]); //
print the largest elemet in each row
}
}
}
OUTPUT :