VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-triangle-from-array/

⇱ Sum triangle from array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum triangle from array

Last Updated : 16 Nov, 2022

Given an array of integers, print a sum triangle from it such that the first level has all array elements. From then, at each level number of elements is one less than the previous level and elements at the level is be the Sum of consecutive two elements in the previous level. 
Example :
 

Input : A = {1, 2, 3, 4, 5}
Output : [48]
 [20, 28] 
 [8, 12, 16] 
 [3, 5, 7, 9] 
 [1, 2, 3, 4, 5] 

Explanation :
Here, [48]
 [20, 28] -->(20 + 28 = 48)
 [8, 12, 16] -->(8 + 12 = 20, 12 + 16 = 28)
 [3, 5, 7, 9] -->(3 + 5 = 8, 5 + 7 = 12, 7 + 9 = 16)
 [1, 2, 3, 4, 5] -->(1 + 2 = 3, 2 + 3 = 5, 3 + 4 = 7, 4 + 5 = 9)


 


Approach : 
 

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

Below is the implementation of the above approach :


Output
48 
20, 28 
8, 12, 16 
3, 5, 7, 9 
1, 2, 3, 4, 5 

Recursive Approach(Without using For loop inside printTriangle() function) :

Approach : 

  1. At each iteration we created a new array(temp []) in printTriangle() function, Which holds the sum of consecutive elements of input array.
  2. Now passed newly created array(temp []) in recursive call of printTriangle() function.
  3. Repeat  step 1 and 2  until size of temp[] array is not equal to 1.

Output
[48]
[20, 28]
[8, 12, 16]
[3, 5, 7, 9]
[1, 2, 3, 4, 5]
Comment
Article Tags: