In: Computer Science
java by using Scite Objectives:
1. Create one-dimensional arrays and two-dimensional arrays to solve problems
2. Pass arrays to method and return an array from a method
Problem 2: Find the largest value of each row of a 2D array
(filename: FindLargestValues.java)
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.
PROGRAM FOR DYNAMIC ARRAY SIZE:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of rows");
int m=sc.nextInt();
System.out.println("Enter number of columns");
int n=sc.nextInt();
int[][] a=new int[m][n];
System.out.println("2D array
is:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=(int)(Math.random()*9);
//take random integer values
System.out.print(a[i][j]+" ");
//print the array
}
System.out.println();
}
int[] r=largestValues(a); //call
the largestValues function
System.out.println("Largest value
of each row for give 2D array:");
for(int
i=0;i<r.length;i++)
{
System.out.println(r[i]);
}
}
public static int[] largestValues(int[][] num)
{
int[] b=new int[num.length];
int max;
for(int i=0;i<num.length;i++)
{
max=0; //set initially largest
value as 0 i.e. max=0
for(int
j=0;j<num[0].length;j++)
{
if(num[i][j]>max)
max=num[i][j];
}
b[i]=max;
}
return b;
}
}
PROGRAM FOR STATIC ARRAY SIZE:
if we give static array size 4x5 as in question statement, see the below program:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int[][] a=new int[4][5];
System.out.println("2D array
is:");
for(int i=0;i<4;i++)
{
for(int j=0;j<5;j++)
{
a[i][j]=(int)(Math.random()*9);
System.out.print(a[i][j]+"
");
}
System.out.println();
}
int[] r=largestValues(a);
System.out.println("Largest value
of each row for give 2D array:");
for(int i=0;i<4;i++)
{
System.out.println(r[i]);
}
}
public static int[] largestValues(int[][] num)
{
int[] b=new int[4];
int max;
for(int i=0;i<4;i++)
{
max=0;
for(int j=0;j<5;j++)
{
if(num[i][j]>max)
max=num[i][j];
}
b[i]=max;
}
return b;
}
}
output:
2D array is:
5 2 6 4 1
6 6 1 1 0
1 2 4 1 3
7 5 3 1 1
Largest value of each row for give 2D array:
6
6
4
7