杨辉三角形

利用二维数组打印一个杨辉三角

案例介绍

①设计打印输出一个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
原文地址:https://www.cnblogs.com/wzy330782/p/5269344.html