Home > Java > javaTutorial > Java uses for loop to output Yang Hui triangle

Java uses for loop to output Yang Hui triangle

高洛峰
Release: 2017-01-22 15:11:50
Original
2579 people have browsed it

The idea is to create an integer two-dimensional array containing 10 one-dimensional arrays. Using a double-level loop, initialize the size of each second-level array in the outer loop. In the inner loop, the array elements on both sides are first assigned the value 1, the other values ​​are calculated through formulas, and then the array elements are output.

public class YanghuiTriangle {
    public static void main(String[] args) {
        int triangle[][]=new int[10][];// 创建二维数组
        // 遍历二维数组的第一层
        for (int i = 0; i < triangle.length; i++) {
            triangle[i]=new int[i+1];// 初始化第二层数组的大小
            // 遍历第二层数组
            for(int j=0;j<=i;j++){
                // 将两侧的数组元素赋值为1
                if(i==0||j==0||j==i){
                    triangle[i][j]=1;
                }else{// 其他数值通过公式计算
                    triangle[i][j]=triangle[i-1][j]+triangle[i-1][j-1];
                }
                System.out.print(triangle[i][j]+"\t");         // 输出数组元素
            }
            System.out.println();               //换行
        }
    }
}
Copy after login

For more java related articles using for loop to output Yang Hui triangle, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template