Traversing 2d array row first and then column first
2d, arrays, java
Solution
Here is one approach that will print by column if the row has that many columns column.
String[][] twoDArray = new String[][] {
new String[] {"Row1Col1", "Row1Col2", "Row1Col3"},
new String[] {"Row2Col1", "Row2Col2"},
new String[] {"Row3Col1", "Row3Col2", "Row3Col3", "Row3Col4"}
};
boolean recordFound = true;
int colIndex = 0;
while(recordFound) {
recordFound = false;
for(int row=0; row<twoDArray.length; row++) {
String[] rowArray = twoDArray[row];
if(colIndex < rowArray.length) {
System.out.println(rowArray[colIndex]);
recordFound = true;
}
}
colIndex++;
}
Output is:
Row1Col1
Row2Col1
Row3Col1
Row1Col2
Row2Col2
Row3Col2
Row1Col3
Row3Col3
Row3Col4
Problem
I am looking for a way to traverse a 2d n by m int array (int[col][row]) first row by row (simple part) and then column by column, in Java. Here is the code for doing row by row, is there a way to do col by col? ``` for(int i = 0; i < display.length; i++){ for (int j = 0; j < display[i].length; j++){ if (display[i][j] == 1) display[i][j] = w++; else w = 0; } } ```