1 Declare a 2D array with double m1020020400 2 Write a metho
1. Declare a 2-D array with
double[][] m={{10,20,0},{20,40,0}};
2. Write a method computeAvg that will take a double 2-D array as the input, compute the average
of 1st and 2nd columns and put the average result at the 3rd column for each row.
3. Write a method printArray to print the values of the 2-D array. The numbers should be aligned.
4. In your main method, call computeAvg first, then call printArray
Solution
public class ArrayAvgCalculation {
public static void main(String[] args) {
double[][] m={{10,20,0},{20,40,0}};
System.out.println(\"Array Before average calculation : \");
printArray(m);
m = computeAvg(m);
System.out.println(\"Array After average calculation : \");
printArray(m);
}
private static double[][] computeAvg(double[][] m) {
double sum = 0.0;
double avg = 0.0;
int i,j;
for(i = 0; i < m[0].length-1; i++){
sum = 0.0;
avg = 0.0;
for(j = 0; j < m.length; j++){
sum += m[j][i]; // column wise sum
}
avg = sum / j; // sum / number of element in the column
m[i][(m[0].length)-1] = avg; //m[0].length)-1 ----> for getting last index of column of array \'m\'
}
return m;
}
private static void printArray(double[][] m) {
for(int i = 0; i < m.length; i++){
for(int j = 0; j < m[i].length; j++){
System.out.print(m[i][j]+\" \");
}
System.out.println();
}
}
}
![1. Declare a 2-D array with double[][] m={{10,20,0},{20,40,0}}; 2. Write a method computeAvg that will take a double 2-D array as the input, compute the average 1. Declare a 2-D array with double[][] m={{10,20,0},{20,40,0}}; 2. Write a method computeAvg that will take a double 2-D array as the input, compute the average](/WebImages/39/1-declare-a-2d-array-with-double-m1020020400-2-write-a-metho-1118851-1761594923-0.webp)