In: Computer Science
Write a Java program that will use a two-dimensional array and modularity to solve the following tasks:
Create a method to fill the 2-dimensional array with (random numbers, range 0 - 30). The array has rows (ROW) and columns (COL), where ROW and COL are class constants.
Create a method to print the array.
Create a method to find the largest element in the array
Create a method to find the smallest element in the array
Create a method to find the sum of all elements in the array
Generate output similar to the sample output below.
Sample Output:
The matrix is:
16 8 23 23
8 22 28 9
23 19 9 19
27 16 27 14
6 11 13 5
The max value for the entire matrix is: 28
package org;
import java.util.Random;
import java.util.Scanner;
public class Matrix {
int ROW;
int COLUMN;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Matrix m=new Matrix();
System.out.println("Enter number of rows: ");
m.ROW=sc.nextInt();
System.out.println("Enter number of columns: ");
m.COLUMN=sc.nextInt();
int[][] a=m.randomArray();
m.printArray(a);
m.largest(a);
m.smallest(a);
m.sum(a);
}
public void largest(int[][] a) {
// TODO Auto-generated method stub
int max=a[0][0];
for(int i=0;i<ROW;i++)
{
for(int j=0;j<COLUMN;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
}
}
}
System.out.println("The largest element in the array is "+max);
}
public void smallest(int[][] a) {
// TODO Auto-generated method stub
int min=a[0][0];
for(int i=0;i<ROW;i++)
{
for(int j=0;j<COLUMN;j++)
{
if(a[i][j]<min)
{
min=a[i][j];
}
}
}
System.out.println("The smallest element in the array is "+min);
}
public void sum(int[][] a) {
// TODO Auto-generated method stub
int sum=0;
for(int i=0;i<ROW;i++)
{
for(int j=0;j<COLUMN;j++)
{
sum=sum+a[i][j];
}
}
System.out.println("The sum of the array is "+sum);
}
public void printArray(int[][] a) {
// TODO Auto-generated method stub
System.out.println("The array is: ");
for(int i=0;i<ROW;i++)
{
for(int j=0;j<COLUMN;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public int[][] randomArray() {
// TODO Auto-generated method stub
int a[][]=new int[ROW][COLUMN];
Random r=new Random();
for(int i=0;i<ROW;i++)
{
for(int j=0;j<COLUMN;j++)
{
a[i][j]=r.nextInt(31);
}
}
return a;
}
}
Output: