java二維陣列定義初始化-楊輝三角

biubiubiuo發表於2018-02-03
public class Array2Demo2_3 {

    public static void main(String[] args) {
        
        //定義初始化
        int[][] arr = new int[3][];//定義高維陣列
        arr[0] = new int[2];//高位陣列下定義低維陣列
        arr[1] = new int[3];
        arr[2] = new int[4];
        
        arr[0][0] = 1;//給低維陣列初始化
        arr[0][1] = 2;
        arr[1][0] = 1;
        arr[1][1] = 2;
        arr[1][2] = 3;
        arr[2][0] = 1;
        arr[2][1] = 2;
        arr[2][2] = 3;
        arr[2][3] = 4;
        
        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();
        }
        //-------------------------楊輝三角----------------------------
        int row = 8;
        int[][] arr1 = new int[row][row];
        for(int i = 0;i<row;i++) {
            for(int j = 0;j<=i;j++) {
                if(j == 0||j == i) {
                    arr1[i][j] =1;
                }else {
                    arr1[i][j] = arr1[i-1][j-1]+arr1[i-1][j];
                }
            }
        }
        
        
        for(int i = 0;i<row;i++) {
            for(int j = 0;j<=i;j++) {
                System.out.print(arr1[i][j]+" ");
            }
            System.out.println();
        }
    }

}

  

相關文章