列印陣列和三角的程式。
生成指定陣列的和三角形
- 從使用者獲取陣列元素(例如 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP