/*
打印杨辉三角
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
.......
思路:
A:构造printSanJiao()函数,用于计算和打印杨辉三角
B:主函数调用printSanJiao();传入杨辉三角层数
*/
class YangHuiSanJiao
{
public static void printSanJiao(int num)
{
//建立二维数组
int[][] arr = new int[num][];
//遍历一维数组
for (int x = 0;x <= num-1 ;x++ )
{
//定义二维数组
arr[x]= new int[x+1];
//两边都是1
arr[x][0] = arr[x][x]=1;
for (int y = 1;y <= x-1 ;y++ )//二维数组的个数是x+1,减去头和尾;y的最大值是y-1
{
arr[x][y] = arr[x-1][y-1]+arr[x-1][y];
}
}
//遍历数组进行打印
for (int x = 0;x <num ;x++ )
{
for (int y = 0;y <=x ;y++ )
{
System.out.print(arr[x][y]);
}
System.out.println();
}
}
public static void main(String[] args)
{
//传递杨辉三角的层数给printSanJiao()函数
printSanJiao(3);
}
}
|
|