1. 程式人生 > 實用技巧 >【JAVA例項】二維陣列來實現楊輝三角的生成和遍歷

【JAVA例項】二維陣列來實現楊輝三角的生成和遍歷

/*
    程式設計使用二維陣列來實現楊輝三角的生成和遍歷
 */

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(); } } }