编程语言
首页 > 编程语言> > Java小练习 输出一个十行的杨辉三角

Java小练习 输出一个十行的杨辉三角

作者:互联网

用二维数组输出一个10行的杨辉三角:
1
11
121
1331
14641
.......
通过观察,不难得到对于杨辉三角中,每行的首,末位元素均为1,而中间的元素yangHui[i][j]=yangHui[i-1][j-1]+yangHui[i-1][j]
所以可以先建立一个二维数组,再按照这种规律依次赋值,最后遍历一遍即可
public class yangHuiTriangle {
    public static void main(String[] args) {
        //声明并初始化二维数组;
        int[][] yangHui = new int[10][];
        for (int i = 0; i < yangHui.length; i++) {
            yangHui[i] = new int[i + 1];
        }
        //给二维数组赋值
        for (int i = 0; i < yangHui.length; i++) {
            //先给边上的赋值
            yangHui[i][0] = 1;
            yangHui[i][i] = 1;
            //再给中间的赋值
            for (int j = 1; j < yangHui[i].length - 1; j++) {
                yangHui[i][j] = yangHui[i - 1][j - 1] + yangHui[i - 1][j];
            }
        }
        //遍历二维数组
        for (int i = 0; i < yangHui.length; i++) {
            for (int j = 0; j < yangHui[i].length; j++) {
                System.out.print(yangHui[i][j] + " ");
            }
            System.out.println();
        }
    }
}

标签:Java,int,++,十行,yangHui,length,数组,杨辉三角,赋值
来源: https://www.cnblogs.com/xianghaoran/p/12229896.html