Program to print Sum Triangle of an array.


To generate a sum triangle of a given array

  • Get the elements of the array from the user say, myArray[n].
  • Create a two dimensional array say, result[n][n].
  • Store the contents of the given array in the first row from bottom of the 2D array.
result[n][i] = myArray[i].
  • Now, from the second row of the 2D array fill elements such that ith element in each row is the sum of ith and (i+1)st elements of the previous row.
result[i][j] = result[i+1][j] + result[i+1][j+1];

Example

 Live Demo

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

Output

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
raja
Published on 12-Jul-2019 12:13:22
Advertisements