二维数组的练习与杨辉三角
public class TestGetSum { public static void main(String[] args) { int[][] m = new int[][] { { 3, 8, 2 }, { 2, 7 }, { 9, 0, 1, 6 } }; int sum = 0; for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) { System.out.print(m[i][j] + " "); sum += m[i][j]; } System.out.println(); } System.out.println("总和:" + sum); } }
输出结果:
3 8 2
2 7
9 0 1 6
总和:38
声明:int [][] x,y[]
一维数组:int[] x
二维数组: int[][] y
杨辉三角:
/* 用二维数组打印一个10行杨辉三角。 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 . . . . . 提示: 第一行 1 个元素,第n行n个元素 每行第一行第一个元素和最后一个元素都是1 第三行开始,对于非第一个元素和最后一个元素的元素 yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j] */ public class TestYangHui { public static void main(String[] args) { int[][] yanghui = new int[10][]; // 初始化数组 for (int i = 0; i < yanghui.length; i++) { yanghui[i] = new int[i + 1]; } // 遍历二维数组 for (int i = 0; i < yanghui.length; i++) { for (int j = 0; j < yanghui[i].length; j++) { yanghui[i][0] = yanghui[i][i] = 1; if (i > 1 && j > 0 && j < i) { yanghui[i][j] = yanghui[i - 1][j - 1] + yanghui[i - 1][j]; } System.out.print(yanghui[i][j] + "\t"); } System.out.println(); } } }
输出结果为:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
All that work will definitely pay off