楊輝三角形,直角楊輝三角形
利用二維數組打印一個楊輝三角

案例介紹
①設計打印輸出一個8行的楊輝三角形
②找出楊輝三角形的特點
案例設計
①二維數組的聲明和使用
②使用for循環來對數組進行賦值和輸出
實施方案
①聲明一個8行8列的數組
②第一列和對角線值為1,其它列的值是其正上方元素和其左上方元素之和。
③對數組進行賦值並打印輸出

![]()
1 public class YangHui{
2 public static void main(String []args){
3 int row=8;//行數
4 int[][] p=new int[row][row];
5 //賦值
6 for(int i=0;i<p.length;i++)
7 {
8 for(int j=0;j<=i;j++)
9 {
10 //第一列和對角線列的元素為1
11 if(j==0||j==i)
12 {
13 p[i][j]=1;
14 }
15 else
16 {
17 //其它元素的值是其正上方與其左上方元素之和
18 p[i][j]=p[i-1][j]+p[i-1][j-1];
19 }
20 }
21 }
22
23 //打印輸出
24 for(int i=0;i<p.length;i++)
25 {
26 for(int j=0;j<=i;j++)
27 {
28 System.out.print(p[i][j]+" ");
29 }
30 System.out.println();
31 }
32 }
33 }
View Code