# Construct a Special Triangle from a Given Array

Objective: Given an array of integers such that first level will print all the elements in the array and from then at each level number of elements will be one less than the previous level and elements at the level will be the Sum of consecutive elements in the previous level. Print it in a reverse level. See Example.

Example:

Approach:

• Recursion is the key.
• At each iteration create a new array which contains the Sum of consecutive elements in the array passes as parameter.
• Make a recursive call and pass the newly created array in the previous step.
• While back tracking print the array (for printing in reverse order)

Code:

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

 import java.util.*; public class ConstructTriangle { public void Triangle(int[] A) { if (A.length >= 1) { int[] temp = new int[A.length – 1]; for (int i = 0; i < A.length – 1; i++) { int x = A[i] + A[i + 1]; temp[i] = x; } Triangle(temp); System.out.println(Arrays.toString(A)); } } public static void main(String[] args) { int[] A = { 1, 2, 3, 4, 5 }; ConstructTriangle c = new ConstructTriangle(); c.Triangle(A); } }

Output:

```
[20, 28]
[8, 12, 16]
[3, 5, 7, 9]
[1, 2, 3, 4, 5]
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.