程序打印数组的和三角形。
生成给定数组的和三角形
从用户说的myArray[n]获取数组的元素。
创建一个二维数组,例如result[n][n]。
将给定数组的内容存储在2D数组底部的第一行中。
result[n][i] = myArray[i].
现在,从2D数组的第二行开始填充元素,以使每行中的第ith个元素是上一行的ith和第(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("输入所需的数组大小:");
int size = sc.nextInt();
int [] myArray = new int[size];
System.out.println("输入数组的元素:");
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();
}
}
}输出结果
输入所需的数组大小: 4 输入数组的元素: 12 25 87 45 393 149 244 37 112 132 12 25 87 45
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短