Program to print Sum Triangle for a given array
Last Updated :
23 Jul, 2025
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++
// 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 Program
int main()
{
int arr[] = {4, 7, 3, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
printTriangle(arr, n);
return 0;
}
Java
// Java program to print sum triangle for a given array
class 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
# 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 Code
if __name__ == '__main__':
arr = [4, 7, 3, 6, 7]
n = len(arr)
printTriangle(arr, n)
# This code is contributed by
# Shashank_Sharma
C#
// C# program to print sum triangle
// for a given array
using 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.
JavaScript
<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>
PHP
<?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
?>
Output81
40 41
21 19 22
11 10 9 13
4 7 3 6 7
Time Complexity: O(n2)
Auxiliary Space: O(n2) because using array "tr"
Thanks to nish for suggesting this solution.
Recursive Approach: We can obtain the sum triangle using recursion by following the steps given below,
- Base case: If n is 0, just return.
- Create a new array b and store the elements of the given array in it.
- Update the new array b, an element b[i] can be calculated as the sum of b[i] and b[i+1].
- Call the function recursively for the new array b.
- Finally, print the elements of the given array.
Below is the implementation of above approach :
C++
// C++ program to print sum triangle for a given array
#include <bits/stdc++.h>
using namespace std;
// recursive funtion to prints
// sum triangle for arr[0..n-1]
void printTriangle(int arr[], int n)
{
// Base case: if n is 0, just return
if (n == 0)
return;
// Initialize a new array to store
// the given array
int b[n];
for (int i = 0; i < n; i++)
b[i] = arr[i];
// modify the array
for (int i = 0; i < n-1; i++) {
b[i] = b[i] + b[i+1];
}
// recursively calling the function
// for new elements of the array
printTriangle(b,n-1);
// print the given array
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << "\n";
}
// Driver Program
int main()
{
int arr[] = { 4, 7, 3, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
printTriangle(arr, n);
return 0;
}
// This code is contributed by abhishekmaran_.
Java
import java.util.Arrays;
public class Main {
// recursive function to print
// sum triangle for arr[0..n-1]
static void printTriangle(int arr[], int n) {
// Base case: if n is 0, just return
if (n == 0)
return;
// Initialize a new array to store
// the given array
int[] b = Arrays.copyOf(arr, n);
// modify the array
for (int i = 0; i < n - 1; i++) {
b[i] = b[i] + b[i + 1];
}
// recursively calling the function
// for new elements of the array
printTriangle(b, n - 1);
// print the given array
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Driver Program
public static void main(String[] args) {
int[] arr = {4, 7, 3, 6, 7};
int n = arr.length;
printTriangle(arr, n);
}
}
JavaScript
// Function to print sum triangle for a given array
function printTriangle(arr, n) {
// Base case: if n is 0, just return
if (n === 0)
return;
// Initialize a new array to store the given array
let b = arr.slice(0, n);
// Modify the array to calculate the sum triangle
for (let i = 0; i < n - 1; i++) {
b[i] = b[i] + b[i + 1];
}
// Recursively call the function for new elements of the array
printTriangle(b, n - 1);
// Print the given array
console.log(arr.slice(0, n).join(" "));
}
// Driver Program
function main() {
let arr = [4, 7, 3, 6, 7];
let n = arr.length;
printTriangle(arr, n);
}
// Call the main function
main();
Python3
# Recursive function to print sum triangle for arr[0..n-1]
def print_triangle(arr, n):
# Base case: if n is 0, just return
if n == 0:
return
# Initialize a new list to store the given array
b = arr[:]
# Modify the array
for i in range(n-1):
b[i] = b[i] + b[i+1]
# Recursively call the function for new elements of the array
print_triangle(b, n-1)
# Print the given array
for i in range(n):
print(arr[i], end=" ")
print()
# Driver Program
if __name__ == "__main__":
arr = [4, 7, 3, 6, 7]
n = len(arr)
print_triangle(arr, n)
Output81
40 41
21 19 22
11 10 9 13
4 7 3 6 7
Time Complexity: O(n2)
Auxiliary Space: O(n2), there are n recursive calls and for each call we are creating a new array of size n.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Print Sum Triangle for a given array
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem