Search code examples
javaarraysprintingconsole

Aligning 2d Array Print Ouput [Java]


I declared a 2D int Array with some values, and I need to invert rows/columns on the Console. The first row has to be shown vertically as the first column, the 2nd row would have to be shown vertically as the 2nd column, and so on. So for example, the values of [0][0] , [0][1] , [0][2] should be printed vertically, and the upcoming values of the 2nd row, should be aligned also vertically just to the right.

Here's my code so far!

public class Print {
    public static void main(String[] args) {

        int firstarray[][] = {{8,9,10,11},{12,13,14,15}};

        System.out.println("This is the inverted array");
        display(firstarray);

    }

public static void display (int x[][]){
    for(int row=0; row<x.length; row++){
        for(int column = 0; column<x[row].length; column++){
            System.out.println(x[row][column] + "\t");
        }
        System.out.print("\n");
    }   
}   
}

Current Output(Not aligned properly):

This is the inverted array
8   
9   
10  
11  

12  
13  
14  
15  

Correct output should be:

This is the inverted array
8,12    
9,13    
10,14   
11,15   

Solution

  • Just change your for loop,

        for(int row=0; row<1; row++){
            for(int column = 0; column<x[row].length; column++){
                System.out.println(x[row][column] + "\t"+x[row+1][column] );
            }
            System.out.print("\n");
        } 
    

    into below this will work even you have 5000 rows,

         for(int row=0; row<x.length-1; row++){
            for (int column = 0; column < x.length; column++) {
                System.out.print(x[column][row] + "\t" );   
                }
                System.out.println();       
          }