Home >Java >Javagetting Started >Java uses a two-dimensional array to print Yang Hui's triangle

Java uses a two-dimensional array to print Yang Hui's triangle

王林
王林forward
2020-09-14 11:08:483372browse

Java uses a two-dimensional array to print Yang Hui's triangle

Purpose:

Use a two-dimensional array to print a 10-line Yang Hui triangle.

(Recommended video tutorial: java course)

Idea:

1. There is 1 element in the first row, and the nth row There are n elements;

2. The first element and the last element of each row are both 1;

3. Starting from the third row, for the non-first element and the last An element of an element. That is: yanghui[i][j] = yanghui[i-1][j-1] yanghui[i-1][j];

Java uses a two-dimensional array to print Yang Huis triangle

This is the array sum For the combination of nested loops, follow the prompts step by step, and the effect is as shown in the picture above.

Code implementation:

package com.atguigu.exer;

import java.util.concurrent.ForkJoinPool;

public class ArrayDemo {
    public static void main(String[] args) {
        //1.二维数组的动态初始化
        int[][] yangHui = new int[10][];

        //2.二维数组的外层元素的动态初始化
        for(int i = 0;i < yangHui.length;i++){
            yangHui[i] = new int[i + 1];
        }

        //3. 给二维数组的内层元素赋值
        for(int i = 0;i < yangHui.length;i++){
            //3.1 每一行的首末元素赋值为1
            yangHui[i][0] = yangHui[i][i] = 1;
            //3.2 每一行的非首末元素赋值。规律为:yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
            //if(i >= 2){
                for(int j = 1;j < yangHui[i].length - 1;j++){
                    yangHui[i][j] = yangHui[i-1][j-1] + yangHui[i-1][j];
                }
            //}

        }

        //4. 遍历二维数组
        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();
        }
    }
}

Related recommendations: java introductory tutorial

The above is the detailed content of Java uses a two-dimensional array to print Yang Hui's triangle. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete