代码:10行的杨辉三角为例
/** * 杨辉三角打印 * * @author yanjq */ public class YangHuiTriangle { public static void main(String[] args) { //打印杨辉三角,层数:10 int[][] arr = new int[10][]; //赋值杨辉三角 for (int i = 0; i < arr.length; i++) { arr[i] = new int[i + 1];//初始化 //首尾元素赋值 arr[i][0] = arr[i][i] = 1; //中间元素赋值 for (int j = 1; j < i; j++) { arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1]; } } //打印杨辉三角 for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[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