In the free response section of U5L4 Extra practice, the following prompt is given:

Do This: Write a reverse method that modifies the parameter instead of returning a new 2D array. For example, if arr contains {{1, 2, 3}, {4, 5, 6}}, then after executing reverse(arr), arr should contain {{6, 5, 4}, {3, 2, 1}}.

The answer key provides the following answer:

public static void reverse(int arr) {

for (int i = 0; i < arr.length / 2; i++) {

for (int j = 0; j < arr[0].length; j++) {

int temp = arr[i][j];

arr[i][j] = arr[arr.length - i - 1][arr[0].length - j - 1];

arr[arr.length - i - 1][arr[0].length - j - 1] = temp;

}

}

}

Our class pointed out that as written, the code will NOT reach the middle row of any array with an ODD number of rows. Coding this in Java Lab confirms the issue. In other words, the middle â€śinnerâ€ť array (or horizontal array) does not get reversed.

Our question is: what is the correct code? Do you have to create a conditional, with one algorithm for â€śevenâ€ť arrays and one for â€śoddâ€ť?

Thank you!

Hello @nlsmith,

Iâ€™m not quite sure what you mean? this example should work in both cases

```
public class ArrayReverse {
public static int[][] reverse(int[][] arr) {
for (int i = 0; i < arr.length / 2; i++) {
for (int j = 0; j < arr[0].length; j++) {
int temp = arr[i][j];
arr[i][j] = arr[arr.length - i - 1][arr[0].length - j - 1];
arr[arr.length - i - 1][arr[0].length - j - 1] = temp;
}
}
return arr;
}
public static void main(String[] args) {
int[][] array2D = {{1,2,3}, {4,5,6}, {7,8,9}};
int[][] flipped2D = reverse(array2D);
for(int i = 0; i < flipped2D.length; i++) {
for(int j = 0; j < flipped2D[i].length; j++) {
System.out.printf("%d", flipped2D[i][j]);
}
System.out.print("\n");
}
}
}
```

for me this solution works perfectly weather itâ€™s even or odd, would you mind elaborating?

I am seeing the issue you and your class found, @nlsmith -

The middle array is not reversed when there is an odd number of rows. I made the two versions to attempt to reverse an array at this link to investigate this issue.

The method I called reverseFirstWay goes through the entire array and reverses it including the middle row if the number of rows is odd. Looking at the output in the console you can see that the 4,5,6 became 6,5,4

The method I called reverseSecondWay is what was on the activity guide that does not hit the middle row when the number of rows is odd-- the 4,5,6 is not reversed.

Best,

Lindsay

1 Like