|NO.Z.00092|——————————|BigDataEnd|——|Java&数组单元.V11|——|Java.v11|二维数组.v03|实现杨辉三角|

一、二维数组实现杨辉三角
### --- 案例题目
~~~     ——>        根据用户输入的行数n输出对应行数的杨辉三角,具体如下:

    1
    1   1
    1   2   1   
    1   3   3   1
    1   4   6   4   1
    1   5   10  10  5   1   
二、编程代码
### --- 编程代码

/*
    编程使用二维数组来实现杨辉三角的生成和遍历
 */
import java.util.Scanner; 
 
public class ArrayArrayTriangleTest {
    
    public static void main(String[] args) {
        
        // 1.提示用户输入一个行数并使用变量记录
        System.out.println("请输入一个行数:");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        
        // 2.根据用户输入的行数来声明对应的二维数组
        int[][] arr = new int[num][];
        
        // 3.针对二维数组中的每个元素进行初始化,使用双重for循环
        // 使用外层for循环控制二维数组的行下标
        for(int i = 0; i < num; i++) {
            // 针对二维数组中的每一行进行内存空间的申请
            arr[i] = new int[i+1];
            // 使用内层for循环控制二维数组的列下标
            for(int j = 0; j <= i; j++) {
                // 当列下标为0或者列下标与当前行的行下标相等时,则对应位置的元素就是1
                if(0 == j || i == j) {
                    arr[i][j] = 1;
                } else {
                    // 否则对应位置的元素就是上一行当前列的元素加上上一行前一列的元素
                    arr[i][j] = arr[i-1][j] + arr[i-1][j-1];
                }
            }
        }
        
        // 4.打印最终生成的结果
        for(int i = 0; i < num; i++) {
            for(int j = 0; j <= i; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
三、编译打印
### --- 编译

C:\Users\Administrator\Desktop\project>javac ArrayArrayTriangleTest.java
### --- 打印输出

C:\Users\Administrator\Desktop\project>java ArrayArrayTriangleTest
请输入一个行数:
8
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

 

posted on   yanqi_vip  阅读(25)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示