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 and the new array that is formed is with 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 content 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

The code runs as it is shown in the example explanation. So for this we need a recursive function that will call itself for every array.

Example

#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++) {
      int x = arr[i] + arr[i + 1];
      temp[i] = x;
   }
   printTriangle(temp, n - 1);
   for (int i = 0; i < n ; i++) {
      if(i == n - 1)
         printf("%d ",arr[i]);
      else
         printf("%d, ",arr[i]);
   }
   printf("
"); } int main() {    int arr[] = { 3,5,7,8,9};    int n = sizeof(arr) / sizeof(arr[0]);    printTriangle(arr, n); }

Output

106
47, 59
20, 27, 32
8, 12, 15, 17
3, 5, 7, 8, 9

Updated on: 09-Aug-2019

517 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements