二维数组树出杨辉三角:打印杨辉三角形(行数可以键盘录入)

public static void printArray(int[][] arr)
{
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();
}
}
package com.company;
import java.util.Scanner;
/**
* Created by ttc on 2017/12/27.
*/
public class Yanghui {
public static void printArray(int[][] arr)
{
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();
}
}
public static void main(String[] args) {
// 分析:看这种图像的规律
// A:任何一行的第一列和最后一列都是1
// B:从第三行开始,每一个数据是它上一行的前一列和它上一行的本列之和。
// 6
// 1
// 1 1
// 1 2 1
// 1 3 3 1
// 1 4 6 4 1
// 1 5 10 10 5 1
Scanner scanner = new Scanner(System.in);
System.out.println("请输入行数");
int row = scanner.nextInt();
int[][] array = new int[row][];
//循环生成的每一行
//A:任何一行的第一列和最后一列都是1
//B:从第三行开始,每一个数据是它上一行的前一列和它上一行的本列之和。
for(int i = 0; i < array.length; i++)
{
array[i] = new int[i+1];
array[i][0] = 1;//第一列设置成1
array[i][i] = 1;//最后一列设置成1
if(i > 1)//从第三行开始
{
for(int j = 1; j <= i-1; j++)
{
array[i][j] = array[i-1][j]/*上一行的本列*/ + array[i-1][j-1]/*上一行的前一列*/;
}
}
}
printArray(array);
}
}
``
网友评论