How to print the elements of a matrix ordered by rows and by columns in Java

1 Answer

0 votes
public class PrintMatrixRowsAndColumns_Java {
    public static void printMatrixRows(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {   
            System.out.printf("row: %d: ", i);
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.printf("%4d ", matrix[i][j]);
            }
            System.out.println();                 
        }
    }
    
    public static void printMatrixColumns(int[][] matrix) {
        for (int j = 0; j < matrix[0].length; j++) { 
            System.out.printf("column %d: ", j);
            for (int i = 0; i < matrix.length; i++) {
                System.out.printf("%4d ", matrix[i][j]);
            }
            System.out.println();                 
        }
    }

    public static void main(String[] args) {
        int[][] matrix = { 
            { 4,   7,  9, 18, 0 },
            { 1,   9, 18, 99, 3 },
            { 9,  17, 89,  2, 5 },
            { 19, 49,  6,  1, 8 }};

        printMatrixRows(matrix);
        
        System.out.println();
        
        printMatrixColumns(matrix); 
    }
}


 
 
/*
run:
 
row: 0:    4    7    9   18    0 
row: 1:    1    9   18   99    3 
row: 2:    9   17   89    2    5 
row: 3:   19   49    6    1    8 

column 0:    4    1    9   19 
column 1:    7    9   17   49 
column 2:    9   18   89    6 
column 3:   18   99    2    1 
column 4:    0    3    5    8 
 
*/

 



answered Jul 12, 2024 by avibootz

Related questions

1 answer 140 views
1 answer 239 views
1 answer 181 views
1 answer 188 views
...