In: Computer Science
2-Dimensional Array Operations.
Use a Java class with a main method.
In this class (after the main method), define and implement the following methods:
In the main method create and initialize a 2-dimensional array of double numbers and test all the methods described above.
public class Main
{
public static void main(String[] args) {
double p[][] =
{{9,7,4},{1,6,3},{4,2,8}}; //Declaring 2d array
printArray(p); //calling printArray
function
double ans;
ans = getAverage(p); //calling
getAverage function and storing result in ans
System.out.println("Average of all
elements is: "+ans); //printing the ans
double sum;
sum = getRowTotal(p,2); //calling
getRowTotal function and storing result in sum
System.out.println("Sum of row is:
"+sum); //printing the sum of row with index 2
double low;
low = getLowestInColumn(p,2);
//calling getLowestInColumn function and storing result in
low
System.out.println("Lowest in
column is: "+low); //printing the low of column with index 2
}
public static void printArray(double p[][])
//printArray function
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(p[i][j]); //printing the
elements
System.out.printf(",");
}
System.out.printf("\n");
}
}
public static double getAverage(double p[][])
//getAverage function
{
double sum=0,ans=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
sum = sum + p[i][j]; //adding the elements
}
}
ans = sum / 9; //calculating the ans
return ans; //returning the ans
}
public static double getRowTotal(double p[][],int q)
//getRowTotal function
{
double ans=0;
ans = p[q][0] + p[q][1] + p[q][2]; //adding the
elements of row
return ans; //returning the ans
}
public static double getLowestInColumn(double
p[][],int q) //getLowestInColumn function
{
if(p[0][q]<p[1][q] && p[0][q]<p[2][q])
//cheking if first element in column is low
return p[0][q];
else if(p[1][q]<p[2][q]) //cheking if second
element in column is low
return p[1][q];
else
return p[2][q];
}
}
Output:-