I have a "connect four board" which I simulate with a 2d array (array[x][y] x=x coordinate, y = y coordinate). I have to use "System.out.println", so I have to iterate through the rows.
I need a way to iterate this way [0,0] [1,0] [2,0] [3,0] [0,1] [1,1] [2,1] etc
If i use the normal procedure:
for (int i = 0; i<array.length; i++){
for (int j = 0; j<array[i].length; j++){
string += array[i][j];
} System.out.println(string)
}
it doesnt work because it iterates this way [0,0] [0,1] [0,2] [0,3] etc
The normal procedure stays in x and increments y until the end of the column, but i need to say in y and increment x until the end of the row.
Consider it as an array of arrays and this will work for sure.
int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
}
}
Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With