Reputation: 11
I wanted to know whether the calculation for average in 2D arrays is the same as 1D arrays? Can I also see a java code for it? This is what I have but I am not getting the correct answer.
static int avgRecursion(int a[][], int i, int j, int f) {
// Last element
if (i == f - 1)
return a[i][j];
// When index is 0, divide sum computed so far by n.
if (i == 0)
return ((a[i][j] + avgRecursion(a, i + 1, j, f)) / f);
// Compute sum
return (a[i][j] + avgRecursion(a, i + 1, j, f));
}
static int[][] array;
static {
array = new int[3][4];
System.out.println("Enter 12 numbers: ");
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = scan.nextInt();
}
}
int f = array.length;
int average = avgRecursion(array, 0, 0, f);
System.out.println("The average of the 2D array: " + average);
}
Upvotes: 1
Views: 1697
Reputation: 820
I am guessing you want to find the average of all the values stored in the 2D array. Here's a small program for that:
public static void main(String[] args) {
int[][] arr = new int[4][5];
int sum = 0;
// Length * Breadth gives total number of elements in array
int arrLength = (arr.length * arr[0].length);
// Populate array
// Your program gets the values from the user
// but i'm hardcoding them. Hope you get the point
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
arr[row][col] = 20;
}
}
// Actual answer starts here
// Calculate sum of all values stored in the array
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
sum += arr[row][col];
}
}
// Print total sum / length of array
System.out.print("The average of the 2D array is " + sum / arrLength);
}
Upvotes: 3
Reputation:
You can flatten the 2D array to one dimension and take the average of the 1D array as usual:
int[][] arr = {{1, 2, 3, 4, 5}, {6, 7, 8}, {9}};
double avg = Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.average()
.orElse(Double.NaN);
System.out.println(avg); // 5.0
Upvotes: 1