Program to print Sum Triangle for a given array

30 Jun, 2022
Given a array, write a program to construct a triangle where last row contains elements of given array, every element of second last row contains sum of below two elements and so on.
Example: 
Input: arr[] = {4, 7, 3, 6, 7};
Output:
81
40 41
21 19 22
11 10 9 13
4 7 3 6 7 

Input: {10, 40, 50}
Output:
140
50 90
10 40 50
An important observation about output is final value is at the top and top element needs to printed first. Therefore, we use a 2D auxiliary array to construct the triangle in bottom up manner and then print the triangle. An element tri[i][j] of 2D array can be calculated as sum of tri[i+1][j] and tri[i+1][j+1].
Below is the implementation of above idea : 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print sum triangle for a given array#include <bits/stdc++.h>using namespace std; // prints sum triangle for arr[0..n-1]void printTriangle(int arr[], int n){    // Initialize a 2D array to store triangle    int tri[n][n];    memset(tri, 0, sizeof(tri));     // Initialize last row of triangle    for (int i = 0; i < n ; i++)        tri[n-1][i] = arr[i];     // Fill other rows    for (int i = n-2; i >=0; i--)      for (int j = 0; j <= i; j++)        tri[i][j] = tri[i+1][j] + tri[i+1][j+1];     // Print the triangle    for (int i = 0; i < n; i++)    {        for(int j = 0; j <= i ; j++)            cout << tri[i][j]<<" ";        cout << endl;    }} // Driver Programint main(){    int arr[] = {4, 7, 3, 6, 7};    int n = sizeof(arr)/sizeof(arr[0]);    printTriangle(arr, n);    return 0;}
// Java program to print sum triangle for a given arrayclass Test{           static int arr[] = new int[]{4, 7, 3, 6, 7};           // prints sum triangle for arr[0..n-1]     public static void printTriangle(int n)     {        // Initialize a 2D array to store triangle        int tri[][] = new int[n][n];                  // Initialize last row of triangle        for (int i = 0; i < n ; i++)            tri[n-1][i] = arr[i];                  // Fill other rows        for (int i = n-2; i >=0; i--)            for (int j = 0; j <= i; j++)               tri[i][j] = tri[i+1][j] + tri[i+1][j+1];                  // Print the triangle        for (int i = 0; i < n; i++)        {            for(int j = 0; j <= i ; j++)                System.out.print(tri[i][j] + " ");            System.out.println();        }     }           public static void main(String[] args)     {         printTriangle(arr.length);        } }
# Python 3 program to print sum triangle# for a given array # prints sum triangle for arr[0..n-1]def printTriangle(arr, n):         # Initialize a 2D array to store triangle    tri = [[0 for i in range(n)]              for i in range(n)]     # Initialize last row of triangle    for i in range(n):        tri[n - 1][i] = arr[i]     # Fill other rows    i = n - 2    while(i >= 0):        for j in range(0, i + 1, 1):            tri[i][j] = (tri[i + 1][j] +                         tri[i + 1][j + 1])                     i -= 1     # Print the triangle    for i in range(0, n, 1):        for j in range(0, i + 1, 1):            print(tri[i][j], end = " ")        print("\n", end = "") # Driver Codeif __name__ == '__main__':    arr = [4, 7, 3, 6, 7]    n = len(arr)    printTriangle(arr, n)     # This code is contributed by# Shashank_Sharma
// C# program to print sum triangle// for a given arrayusing System; class GFG {         static int []arr = new int[]{4, 7, 3, 6, 7};         // prints sum triangle for arr[0..n-1]    public static void printTriangle(int n)    {        // Initialize a 2D array to store triangle        int [,]tri = new int[n, n];                 // Initialize last row of triangle        for (int i = 0; i < n ; i++)            tri[n - 1, i] = arr[i];                 // Fill other rows        for (int i = n - 2; i >= 0; i--)            for (int j = 0; j <= i; j++)            tri[i, j] = tri[i + 1, j] +                        tri[i + 1, j + 1];                  // Print the triangle        for (int i = 0; i < n; i++)        {            for(int j = 0; j <= i ; j++)                Console.Write(tri[i, j] + " ");                Console.WriteLine();        }    }         // Driver Code    public static void Main()    {        printTriangle(arr.Length);    }} // This code is contributed by Sam007.
<?php// PHP program to print sum// triangle for a given array // prints sum triangle for arr[0..n-1]function printTriangle($arr, $n){    // Initialize a 2D array to store triangle    $tri[$n][$n] = array(array());    array_fill(0, count($tri), 0);     // Initialize last row of triangle    for ($i = 0; $i < $n ; $i++)        $tri[$n - 1][$i] = $arr[$i];     // Fill other rows    for ($i = $n - 2; $i >= 0; $i--)    for ($j = 0; $j <= $i; $j++)        $tri[$i][$j] = $tri[$i + 1][$j] +                       $tri[$i + 1][$j + 1];     // Print the triangle    for ($i = 0; $i < $n; $i++)    {        for( $j = 0; $j <= $i ; $j++)            echo $tri[$i][$j] . " ";        echo "\n";    }} // Driver Code$arr = array(4, 7, 3, 6, 7);$n = count($arr);printTriangle($arr, $n); // This code is contributed by Rajput-Ji?>
<script>      // JavaScript program to print sum triangle for a given array       // prints sum triangle for arr[0..n-1]      function printTriangle(arr, n)      {               // Initialize a 2D array to store triangle        var tri = new Array(n).fill(0).map((item) => new Array(n).fill(0));         // Initialize last row of triangle        for (var i = 0; i < n; i++) tri[n - 1][i] = arr[i];         // Fill other rows        for (var i = n - 2; i >= 0; i--)          for (var j = 0; j <= i; j++)            tri[i][j] = tri[i + 1][j] + tri[i + 1][j + 1];         // Print the triangle        for (var i = 0; i < n; i++) {          for (var j = 0; j <= i; j++)            document.write(tri[i][j] + "  ");          document.write("<br>");        }      }       // Driver Program      var arr = [4, 7, 3, 6, 7];      var n = arr.length;      printTriangle(arr, n);             // This code is contributed by rdtank.    </script>
Output: 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
81
40 41
21 19 22
11 10 9 13
4 7 3 6 7
Time Complexity: O(n2)
Print Sum Triangle for a given array | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrint Sum Triangle for a given array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=anyBv3m2emQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Thanks to nish for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Sam007
Shashank_Sharma
Rajput-Ji
rdtank
anikakapoor
akashish__
triangle
Arrays
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++