// arrays and methods public class array_methods0 { public static void main(String[] args) { int[][] x = { {1, 2, 3}, {4, 5}, {6, 7, 8, 9} }; int[][] y = { {9, 8, 7}, {6, 5}, {4, 3, 2, 1} }; print( add(x, y) ); } // method main // print 1D array public static void print(int[] x) { System.out.println(); for (int i=0; i<x.length; i++) System.out.print(x[i] + " "); } // method print // print 2D array public static void print(int[][] x) { for (int i=0; i<x.length; i++) print(x[i]); System.out.println(); } // method print // add 1D arrays public static int[] add(int[] x, int[] y) { // assuming x and y have same length! int[] tmp = new int[x.length]; for (int i=0; i<x.length; i++) tmp[i] = x[i] + y[i]; return tmp; } // method add (1D) // add 2D arrays public static int[][] add(int[][] x, int[][] y) { // columns might be different lengths, but assume col x = col y // use tmp to store results of 2-D array addition // create enough space for each row: int[][] tmp = new int[x.length][]; for(int i=0; i<x.length; i++) { tmp[i] = new int[x[i].length]; // create row tmp[i] = add(x[i],y[i]); // add each row } return tmp; } // method add (2D) /* Long form of add(int[][] x, int[][] y) method: public static int[][] add(int[][] x, int[][] y) { // use tmp to store results of 2-D array addition // create enough space for each row: int[][] tmp = new int[x.length][]; for(int i=0; i<x.length; i++) tmp[i] = new int[x[i].length]; // create row for(int i=0; i<x.length; i++) for(int j=0; j<x.length; j++) tmp[i][j] = x[i][j] + y[i][j]; return tmp; } */ } // class array_methods /* output: 10 10 10 10 10 10 10 10 10 */