Open In App

Sum triangle from array

Improve
Improve
Like Article
Like
Save
Share
Report

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 :

C++




// C++ program to create Special triangle.
#include<bits/stdc++.h>
using namespace std;
   
// Function to generate Special Triangle
void printTriangle(int A[] , int n)
    {
        // Base case
        if (n < 1)
            return;
   
        // Creating new array which contains the
        // Sum of consecutive elements in
        // the array passes as parameter.
        int temp[n - 1];
        for (int i = 0; i < n - 1; i++)
        {
            int x = A[i] + A[i + 1];
            temp[i] = x;
        }
   
        // Make a recursive call and pass
        // the newly created array
        printTriangle(temp, n - 1);
   
        // Print current array in the end so
        // that smaller arrays are printed first
        for (int i = 0; i < n ; i++)
        {
            if(i == n - 1)
                cout << A[i] << " ";
            else
            cout << A[i] << ", ";
        }
                   
        cout << endl;
    }
   
    // Driver function
    int main()
    {
        int A[] = { 1, 2, 3, 4, 5 };
        int n = sizeof(A) / sizeof(A[0]);
           
        printTriangle(A, n);
    }
       
// This code is contributed by Smitha Dinesh Semwal


Java




// Java program to create Special triangle.
import java.util.*;
import java.lang.*;
   
public class ConstructTriangle
{
    // Function to generate Special Triangle.
    public static void printTriangle(int[] A)
    {
        // Base case
        if (A.length < 1)
            return;
   
        // Creating new array which contains the
        // Sum of consecutive elements in
        // the array passes as parameter.
        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;
        }
   
        // Make a recursive call and pass
        // the newly created array
        printTriangle(temp);
   
        // Print current array in the end so
        // that smaller arrays are printed first
        System.out.println(Arrays.toString(A));
    }
   
    // Driver function
    public static void main(String[] args)
    {
        int[] A = { 1, 2, 3, 4, 5 };
        printTriangle(A);
    }
}


Python3




# Python3 program to create Special triangle.
# Function to generate Special Triangle.
def printTriangle(A):
           
        # Base case
        if (len(A) < 1):
            return
   
        # Creating new array which contains the
        # Sum of consecutive elements in
        # the array passes as parameter.
        temp = [0] * (len(A) - 1)
        for i in range( 0, len(A) - 1):
           
            x = A[i] + A[i + 1]
            temp[i] = x
           
   
        # Make a recursive call and pass
        # the newly created array
        printTriangle(temp)
           
        # Print current array in the end so
        # that smaller arrays are printed first
        print(A)
       
   
# Driver function
A = [ 1, 2, 3, 4, 5 ]
printTriangle(A)
   
# This code is contributed by Smitha Dinesh Semwal


C#




// C# program to create Special triangle.
    
using System;
                       
public class ConstructTriangle
{
// Function to generate Special Triangle
static void printTriangle(int []A, int n)
    {
        // Base case
        if (n < 1)
            return;
    
        // Creating new array which contains the
        // Sum of consecutive elements in
        // the array passes as parameter.
        int []temp = new int[n - 1];
        for (int i = 0; i < n - 1; i++)
        {
            int x = A[i] + A[i + 1];
            temp[i] = x;
        }
    
        // Make a recursive call and pass
        // the newly created array
        printTriangle(temp, n - 1);
    
        // Print current array in the end so
        // that smaller arrays are printed first
        for (int i = 0; i < n ; i++)
        {
            if(i == n - 1)
                Console.Write(A[i] + " ");
            else
            Console.Write(A[i] + ", ");
        }
                    
        Console.WriteLine();
    }
    
    // Driver function
    public static void Main()
    {
        int[] A = { 1, 2, 3, 4, 5 };
        int n = A.Length;
        printTriangle(A,n);
    }
}
   
//This code contributed by 29AjayKumar


PHP




<?php
// PHP program to create
// Special triangle.
   
// Function to generate
// Special Triangle
function printTriangle($A , $n)
    {
       
        // Base case
        if ($n < 1)
            return;
   
        // Creating new array which
        // contains the Sum of
        // consecutive elements in
        // the array passes as parameter.
        $temp[$n - 1] = 0;
        for ($i = 0; $i < $n - 1; $i++)
        {
            $x = $A[$i] + $A[$i + 1];
            $temp[$i] = $x;
        }
   
        // Make a recursive call and
        // pass the newly created array
        printTriangle($temp, $n - 1);
   
        // Print current array in the
        // end so that smaller arrays
        // are printed first
        for ($i = 0; $i < $n ; $i++)
        {
            if($i == $n - 1)
                echo $A[$i] , " ";
            else
            echo $A[$i] , ", ";
        }
                   
        echo "\n";
    }
   
// Driver Code
$A = array( 1, 2, 3, 4, 5 );
$n = sizeof($A);
   
printTriangle($A, $n);
   
// This code is contributed
// by nitin mittal.
?>


Javascript




<script>
 
// JavaScript program to create Special triangle.
 
// Function to generate Special Triangle
 function printTriangle(A,  n)
    {
        // Base case
        if (n < 1)
            return;
    
        // Creating new array which contains the
        // Sum of consecutive elements in
        // the array passes as parameter.
        var temp = new Array(n - 1);
        for (var i = 0; i < n - 1; i++)
        {
            var x = A[i] + A[i + 1];
            temp[i] = x;
        }
    
        // Make a recursive call and pass
        // the newly created array
        printTriangle(temp, n - 1);
    
        // Print current array in the end so
        // that smaller arrays are printed first
        for (var i = 0; i < n ; i++)
        {
            if(i == n - 1)
                document.write( A[i]  + " ");
            else
            document.write( A[i]  + ", ");
        }
                    
        document.write("<br>");
    }
    
    // Driver function
 
         var A = [ 1, 2, 3, 4, 5 ];
        var n = A.length;
        printTriangle(A,n);
 
</script>


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.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to fill elements in temp Array//
int* helper(int temp[], int x[], int index, int n)
{
   
    // base condition//
    if (index == n - 1) {
        return temp;
    }
    temp[index] = x[index] + x[index + 1];
   
    // Recursive Call for helper() function//
    return helper(temp, x, index + 1, n);
}
void printTriangle(int x[], int n)
{
   
    // base condition
    if (n == 1) {
        return;
    }
   
    /*temprory Array of input array in print(int[] arr)
    function for example arr = {1,2,3,4,5} then temp[] =
    {3,5,7,9} of size(arr.length-1)=4*/
    int* temp = new int[n - 1];
   
    // Recursive function to fill elements in temp Array
    // according to Que.
    helper(temp, x, 0, n);
   
    // Recursive call for print(int[] arr) function
    printTriangle(temp, n - 1);
   
    // prints String format of temp Array//
    for (int i = 0; i < n - 1; i++) {
        cout << temp[i] << " ";
    }
    cout << endl;
}
 
int main()
{
   
    // input Array
    int x[] = { 1, 2, 3, 4, 5 };
   
    // Recursive function that will print answer
    printTriangle(x, 5);
    for (int i = 0; i < 5; i++) {
        cout << x[i] << " ";
    }
    cout << endl;
}
 
// This code is contributed by garg28harsh.


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
class GFG {
  public static void main(String[] args)
  {
    //input Array
    int[] x = { 1, 2, 3, 4, 5 };
    //Recursive function that will print answer
    printTriangle(x);
    System.out.println(Arrays.toString(x));
  }
static void printTriangle(int[] x)
{
    //base condition
    if (x.length == 1) {
        return;
    }
    /*temprory Array of input array in print(int[] arr) function
    for example arr = {1,2,3,4,5}
    then temp[] = {3,5,7,9} of size(arr.length-1)=4*/
    int[] temp = new int[x.length - 1];
    //Recursive function to fill elements in temp Array according to Que. 
    helper(temp, x, 0);
    //Recursive call for print(int[] arr) function
    printTriangle(temp);
    //prints String format of temp Array//
    System.out.println(Arrays.toString(temp));
}
  //Recursive function to fill elements in temp Array//
static int[] helper(int[] temp, int[] x, int index)
{
    //base condition//
    if (index == x.length - 1) {
        return temp;
    }
    temp[index] = x[index] + x[index + 1];
    //Recursive Call for helper() function//
    return helper(temp, x, index + 1);
}
}
//This Code is Contributed by Pradeep_6036 from YMCA//


Python3




# Python code to implement the approach
def printTriangle(x):
   
    # base condition
    if(len(x) == 1):
        return
       
    # temporary array of input array in print(int[] arr) function
    # for example arr = { 1, 2, 3, 4, 5 }
    # then temp[] = { 3, 5, 7, 9 } of size(len(arr)-1)= 4
    temp = [0]*(len(x)-1)
     
    # Recursive function to fill elements in temp array according to Que.
    helper(temp, x, 0)
     
    # Recursive call for print(int[] arr) function
    printTriangle(temp)
     
    # prints string format of temp array
    print(temp)
 
# Recursive function to fill elements in temp array
def helper(temp, x, index):
   
    # base condition
    if(index == len(x)-1):
        return temp
    temp[index] = x[index] + x[index + 1]
     
    # Recursive call for helper() function
    return helper(temp, x, index + 1)
 
 
x = [1, 2, 3, 4, 5]
 
# Recursive function that will print answer
printTriangle(x)
print(x)
 
# This code is contributed by lokeshmvs21.


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
  // Recursive function to fill elements in temp Array//
  static int[] helper(int[] temp, int[] x, int index,
                      int n)
  {
 
    // base condition//
    if (index == n - 1) {
      return temp;
    }
    temp[index] = x[index] + x[index + 1];
 
    // Recursive Call for helper() function//
    return helper(temp, x, index + 1, n);
  }
  static void printTriangle(int[] x, int n)
  {
 
    // base condition
    if (n == 1) {
      return;
    }
 
    /*temprory Array of input array in print(int[] arr)
        function for example arr = {1,2,3,4,5} then temp[] =
        {3,5,7,9} of size(arr.length-1)=4*/
    int[] temp = new int[n - 1];
 
    // Recursive function to fill elements in temp Array
    // according to Que.
    helper(temp, x, 0, n);
 
    // Recursive call for print(int[] arr) function
    printTriangle(temp, n - 1);
 
    // prints String format of temp Array//
    for (int i = 0; i < n - 1; i++) {
      Console.Write(temp[i] + " ");
    }
    Console.WriteLine("");
  }
 
  // Driver code
  public static void Main(string[] args)
  {
 
    // input Array
    int[] x = { 1, 2, 3, 4, 5 };
 
    // Function Call
    printTriangle(x, 5);
    for (int i = 0; i < 5; i++)
      Console.Write(x[i] + " ");
 
    return;
  }
}
 
// This code is contributed by garg28harsh.


Javascript




<script>
// Recursive function to fill elements in temp Array//
function helper( temp, x, index, n)
{
   
    // base condition//
    if (index == n - 1) {
        return temp;
    }
    temp[index] = x[index] + x[index + 1];
   
    // Recursive Call for helper() function//
    return helper(temp, x, index + 1, n);
}
function printTriangle( x,  n)
{
   
    // base condition
    if (n == 1) {
        return;
    }
   
    /*temprory Array of input array in print(int[] arr)
    function for example arr = {1,2,3,4,5} then temp[] =
    {3,5,7,9} of size(arr.length-1)=4*/
    let temp = [];
    for(let i = 0; i < n - 1; i++)
    {temp.push(0);}
   
    // Recursive function to fill elements in temp Array
    // according to Que.
    helper(temp, x, 0, n);
   
    // Recursive call for print(int[] arr) function
    printTriangle(temp, n - 1);
   
    // prints String format of temp Array//
    document.write(temp);
}
 
    // input Array
    let x = [1, 2, 3, 4, 5 ];
   
    // Recursive function that will print answer
    printTriangle(x, 5);
    document.write(x);
   
  // This code is contributed by garg28harsh.
</script>


Output

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


Last Updated : 16 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads