列印陣列和三角的程式。


生成指定陣列的和三角形

  • 從使用者獲取陣列元素(例如 myArray[n])。
  • 建立一個二維陣列(例如 result[n][n])。
  • 將指定陣列的內容儲存在二維陣列底行的第一行中。
result[n][i] = myArray[i].
  • 現在,從二維陣列的第二行開始填充元素,使得每一行中第 i 個元素是前一行的第 i 和第 (i+1) 個元素之和。
result[i][j] = result[i+1][j] + result[i+1][j+1];

示例

 實際演示

import java.util.Scanner;
public class SumTriangleOfAnArray {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the required size of the array :");
      int size = sc.nextInt();
      int [] myArray = new int[size];
      System.out.println("Enter elements of the array :");
      for(int i = 0; i< size; i++){
         myArray[i] = sc.nextInt();
      }
      int[][] result = new int [size][size];
      for(int i = 0; i<size; i++){
         result[size-1][i] = myArray[i];
      }
      for (int i=size-2; i >=0; i--){
         for (int j = 0; j <= i; j++){
            result[i][j] = result[i+1][j] + result[i+1][j+1];
         }
      }
      for (int i=0; i<result.length; i++){
         for (int j=0; j<size; j++){
            if(result[i][j]!= 0){
               System.out.print(result[i][j]+" ");
            }
         }
         System.out.println();
      }
   }
}

輸出

Enter the required size of the array :
4
Enter elements of the array :
12
25
87
45
393
149 244
37 112 132
12 25 87 45

更新日期:30-07-2019

438 次瀏覽

開啟你的 職業生涯

透過完成課程進行認證

開始學習
廣告