Sample Program - 2D Arrays as Parameters
// this program uses several functions with 2D arrays as parameters public class ArrayParm { public static void main(String[] args) { // create a rectangular array, fill it with values, and print it int[][] nums = new int[5][6]; fill(nums); display(nums); System.out.println(); // create a lower triangular array and print it int[][] lower = new int[5][]; for (int i = 0 ; i < 5 ; i++) lower[i] = new int[i+1]; fill(lower); display(lower); } // store a value in each location of a 2D array // works for any 2D array, even if the rows are not the same size public static void fill(int[][] nums) { for (int i = 0 ; i < nums.length ; i++) for (int j = 0 ; j < nums[i].length ; j++) nums[i][j] = (i + j + 1); } // print a 2D array // works for any 2D array, even if the rows are not the same size public static void display(int[][] arr) { for (int i = 0 ; i < arr.length ; i++) { for (int j = 0 ; j < arr[i].length ; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } }Output:
1 2 3 4 5 6 2 3 4 5 6 7 3 4 5 6 7 8 4 5 6 7 8 9 5 6 7 8 9 10 1 2 3 3 4 5 4 5 6 7 5 6 7 8 9
Email Me | Office Hours | My Home Page | Department Home | MCC Home Page