How to pass 2D array (matrix) to function in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int[][] matrix = {{31, 22, 33}, 
                          {42, 85, 987}};
 
        print_array(matrix);
    }
    public static void print_array(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++)
                 System.out.format("%4d", matrix[i][j]);
            System.out.println();
        }
    }
}
 
/*
                
run:
   
  31  22  33
  42  85 987
       
*/

 



answered Apr 14, 2018 by avibootz

Related questions

1 answer 183 views
1 answer 240 views
1 answer 160 views
1 answer 159 views
1 answer 148 views
1 answer 140 views
1 answer 143 views
...