Java // 使用二维数组打印 10 行杨辉三角

 1             // 使用二维数组打印 10 行杨辉三角
 2             public static void main(String[] args) 
 3             {
 4                 //1.声明 并初始化二维数组
 5                 int[][]yanghui = new int[10][];
 6                 
 7                 
 8                 
 9                 //2.给数组元素赋值
10                 for(int i = 0; i<yanghui.length;i++)
11                 {
12                     yanghui[i] = new int[i +1 ];
13                 
14                 //2.1给首末元素赋值
15                 yanghui[i][0] = 1;
16                 yanghui[i][i]=1;
17                 
18                 //2.2给每行的非首末元素赋值
19                 if(i>1)
20                 {
21                     for(int j =1;j<yanghui[i].length-1;j++)
22                     {
23                         yanghui[i][j] = yanghui[i-1][j-1]+yanghui[i-1][j];
24                     }
25                 }
26                 
27             }
28                 
29                 
30                 //3.遍历二维数组
31                 for(int i =0;i<yanghui.length;i++)
32                 {
33                     for(int j = 0;j <yanghui[i].length;j++)
34                     {
35                         System.out.print(yanghui[i][j]+" ");
36                     }
37                     System.out.println();
38                 
39                 
40             }

 

posted on 2021-09-03 14:36  Bytezero!  阅读(228)  评论(0编辑  收藏  举报