Home > Software design >  Trying to print out 2d array by columns in Java
Trying to print out 2d array by columns in Java

Time:12-04

I'm just not seeing this correctly. I can't get it to loop through and print out in column order like [0][0] [1][0] [2][0] [3][0] etc...

public class Assign8 {
//Declare static array intar
static int [][] intar = {{10, 13, 26, 34, 60, 90}, {25, 46, 57, 88, 77, 91}, {29, 30, 41, 52, 82, 92}};


public static void main(String[] args) {
    //Call printArrayAsIs method
    printArrayAsIs();
    System.out.println();
    //Call printArrayColumnWise method
    printArrayColumnWise();

}

//Method to print out full array in one line
public static void printArrayAsIs(){
    for (int i = 0; i < intar.length; i  ) {
        //Loop through all rows of array
        for (int j = 0; j < intar[i].length; j  )
            System.out.print(intar[i][j]   " ");
        }
}

public static void printArrayColumnWise(){
    for (int j = 0; j < intar.length; j  ) {
    // Loop through all columns of array
        for (int i = 0; i < intar[j].length; i  )
            System.out.print(intar[i][j]   " ");
    }
}

}

CodePudding user response:

In your loops you need to think about what each value represents. For your outer loop the limit should be the number of columns. In my implementation I did the number of columns in the first row, since all rows have the same amount of columns. For the second loop the limit is simply the number of rows.

public static void printArrayColumnWise(){
    for (int j = 0; j < intar[0].length; j  ) {
    // Loop through all columns of array
        for (int i = 0; i < intar.length; i  )
            System.out.print(intar[i][j]   " ");
    }
}

CodePudding user response:

It would help if you name your for loop variables "row" and "col" (instead of i and j). Then when you access the array, with intar[row][col], it's really clear what is happening.

You need to iterate over columns first, then the rows, so you have swap the positions of your for loops in your original code, with columns in the outer loop position and rows in the nested loop position:

  public static void printArrayColumnWise(){
    for (int col = 0; col < intar[0].length; col  ) {
      for (int row = 0; row < intar.length; row  ) {
        System.out.print(intar[row][col]   " ");
      }
    }
  }

*This is essentially the same as what Erik McKelvey already posted!

  •  Tags:  
  • java
  • Related