Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing 2d array row first and then column first

Tags:

java

arrays

2d

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;
            }
        }
like image 960
AlexK Avatar asked Dec 25 '22 14:12

AlexK


1 Answers

Since you used a two dimensional array as a matrix, we can assume that the length of each row is the same throughout the matrix (i.e. number of columns of each row is the same).

//So, you can treat display[0].length as the number of columns.

for(int col=0; col<display[0].length; col++)
{
   for(int row=0; row<display.length; row++)
   {
      //your code to access display[row][col]
   }
}

Hope this helps!

like image 55
garyF Avatar answered Jan 06 '23 07:01

garyF