Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum triangle from an array in C programming
The sum triangle from an array is a triangle that is made by decreasing the number of elements of the array one by one. The new array that is formed contains integers that are the sum of adjacent integers of the existing array. This procedure continues until only one element remains in the array.
Let's take an example to explain the concept better −
Array = [3, 5, 7, 8, 9]
Output
[106] [47, 59] [20, 27, 32] [8, 12, 15, 17] [3, 5, 7, 8, 9]
Explanation
For the first array: (3 + 5 = 8), (5 + 7 = 12), (7 + 8 = 15), (8 + 9 = 17) For the second array: 8 + 12 = 20, 12 + 15 = 27, 15 + 17 = 32 For the third array: 20 + 27 = 47, 27 + 32 = 59 For the final array: 47 + 59 = 106
Syntax
void printTriangle(int arr[], int n);
Example: Using Recursive Approach
This approach uses a recursive function that calls itself for every array level, building the triangle from bottom to top −
#include <stdio.h>
void printTriangle(int arr[], int n) {
if (n < 1) {
return;
}
int temp[n - 1];
for (int i = 0; i < n - 1; i++) {
temp[i] = arr[i] + arr[i + 1];
}
printTriangle(temp, n - 1);
printf("[");
for (int i = 0; i < n; i++) {
if (i == n - 1)
printf("%d", arr[i]);
else
printf("%d, ", arr[i]);
}
printf("]<br>");
}
int main() {
int arr[] = {3, 5, 7, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
printTriangle(arr, n);
return 0;
}
[106] [47, 59] [20, 27, 32] [8, 12, 15, 17] [3, 5, 7, 8, 9]
How It Works
- The recursive function first creates a temporary array with n-1 elements.
- Each element in the temp array is the sum of two adjacent elements from the current array.
- The function calls itself recursively with the new temp array until only one element remains.
- During the return phase of recursion, each level prints its array, creating the triangle pattern.
Conclusion
The sum triangle is effectively created using recursion, where each recursive call reduces the array size by one and creates a new level. The triangle is printed in reverse order due to the recursive nature of the algorithm.
