1

I can get a row from a 2D array in java by foreach loop like :

        int[][] array = new int[5][5] 
        for (int[] row : array) {
        for (int c : row) {
        }
        }

But How can I get the column form 2D array by foreach loop ? Or is this possible to get column from 2D array by foreach loop ?

Thank you.

2
  • Can you clarify the question? Do you want the index of the column, using foreach means you dont get an index. If you want the index use a traditional for loop. Commented Feb 28, 2016 at 9:23
  • Are you sure that your array is a perfect square matrix (N x N) of same length and width. Commented Feb 28, 2016 at 9:43

3 Answers 3

4

One alternative can be

    int i =0;
    for (int k : array[0]){
        for (int[] row : array) {
            System.out.println(row[i]);
        }
        i++;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This is a clever one. :D
1

It's not possible. You'll have to use the traditional for loop :

int[][] array = new int[5][5] 
for (int j = 0; j < array[0].length; j++) {
    for (int i = 0; i < array.length; i++) {
        int current = array[i][j];
    }
}

Comments

0

2D array is just a conceptual meaning. in fact 2d array is a combination of multiple one-dimensional array. Therefore you cannot access the columns without using a counter. even if you use for each loop you need a counter inside.

If you need to get all the columns then you can make a loop with number of column. But in this case all the rows should have the same number of columns (elements)

public static void main(String[] args)
{
    int [][] yourArray = {{1,2,3,4,5,6},//sample 2d array with 6 rows and six columns
                    {1,2,3,4,5,6},      //this is actually a collection of 6 different 1d arrays
                    {1,2,3,4,5,6},
                    {1,2,3,4,5,6},
                    {1,2,3,4,5,6},
                    {1,2,3,4,5,6}};

    int yourColumn = 3; //example of selected column (be careful columns start from 0)

    for(int[] row: yourArray)
    {
        System.out.println(row[yourColumn]);
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.