Chi Hian Chan
Chi Hian Chan

Reputation: 17

How to loop vertically through a 2d array in java

Supposedly i want to loop through the 2d array vertically for example given a 2*2 array

How do i output the values accordingly to the bold part

Upvotes: 0

Views: 1874

Answers (2)

Sravya
Sravya

Reputation: 66

Since you want to loop through the array vertically by changing the first dimension, you need to have the variable in the inner for loop to be the first dimension like the code below:

for(int i=0; i<3; i++){
             for(int j=0; j<3; j++){
                 System.out.println(a[j][i]);
             }
         }

Upvotes: 1

parthlr
parthlr

Reputation: 426

for (int i = 0; i < a.length; i++) {
    System.out.print(a[i][0]);
}

Of course, you can replace the 0 with any in-bounds column.

Upvotes: 3

Related Questions