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 generate a 2-dimensional array (random numbers, range 0 - 500). The array has ROW rows and COL columns, 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
import java.io.*;
import java.util.*;
class TwoDArrayStats
{
public static final int ROW = 10;
public static final int COL = 10;
//Create a method to print the array.
public static void printArray(int[][] A)
{
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
System.out.printf("%4d ", A[i][j]);
System.out.println();
}
}
//Create a method to find the largest element in the array.
public static int findLarge(int[][] A)
{
int large = A[0][0];
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
if(A[i][j] > large)
large = A[i][j];
return large;
}
//Create a method to find the smallest element in the array.
public static int findSmall(int[][] A)
{
int small = A[0][0];
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
if(A[i][j] < small)
small = A[i][j];
return small;
}
//Create a method to find the sum of all elements in the
array.
public static int summation(int[][] A)
{
int sum = 0;
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
sum += A[i][j];
return sum;
}
public static void main(String[] args)
{
Random ran = new Random();
int[][] Array = new int[ROW][COL];
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
Array[i][j] = ran.nextInt(501);
System.out.println("The random element array is: ");
printArray(Array);
System.out.print("The largest element in the array is:
"+findLarge(Array));
System.out.println();
System.out.print("The smallest element in the array is:
"+findSmall(Array));
System.out.println();
System.out.println("The sum of the elements in the array is:
"+summation(Array));
System.out.println();
}
}