# 2D ARRAY PROBLEM

• June 27th, 2011, 07:10 PM
av8
2D ARRAY PROBLEM
I have a 2D array called box.

Code :

`int[][] box = new int [2][3];`

Its has elements as follows:

Code :

```box [0][0] = 1; box [0][1] = 2; box [0][2] = 3; box [1][0] = 1; box [1][1] = 2; box [1][2] = 3;```

I want to end up after coding with elements in the array as follows:
Code :

```box [0][0] = 2; box [0][1] = 3; box [0][2] = 3; box [1][0] = 2; box [1][1] = 3; box [1][2] = 3;```
i.e All elements in each column has had its values
replaced by values from its immediate right hand column

I have tried :
Code :

```for (int j = 0; j < box.length - 1; j++) for (int i = 0; i < box.length - 1; i++) box[i][j] = box[i] [j + 1];```
but no joy. Any thoughts please??
• June 27th, 2011, 08:02 PM
Junky
Re: 2D ARRAY PROBLEM
Quote:

Originally Posted by av8
but no joy.

That provides zero information. Presumably your code didn't work. Since there is a gazillion reasons why it didn't work we have no idea what your problem is. If you provide details it will help others help you.

Hint: a 2D array is simply a 1D array of 1D arrays.
Code java:

```int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}}; for(int outer = 0; outer < matrix.length; outer++) { int[] temp = matrix[outer]; for(int inner = 0; inner < temp.length; inner++) { System.out.print(temp[inner] + " "); } System.out.println(); }```
So you can concentrate on 1 dimension instead of 2.
• June 27th, 2011, 08:15 PM
av8
Re: 2D ARRAY PROBLEM
for (int j = 0; j < 2; j++)
for (int i = 0; i < 1; i++)
box[i][j] = box[i] [j + 1];

The above code is now working correctly. Thanks for commenting Junky.

kind regards av8
• June 27th, 2011, 08:20 PM
Junky
Re: 2D ARRAY PROBLEM
Do not hard code values like that. It will not work for a 2D array of any other size.