Programs


Title : Program to count the number of triangles from a given array

#include <stdio.h>

#include <stdlib.h>

int compare(const void *one, const void *two)

{

   return *(int *)one > *(int *)two;

}

int CountNumberOfTriangles(int *arr1, int arr_size)

{

   int ctrTriangle = 0, i, j, k;

   qsort(arr1, arr_size, sizeof(int), compare);

   for (i = 0; i < arr_size - 2; ++i)

   {

       for (j = i + 1; j < arr_size; ++j)

       {

           k = j + 1;

           while (k < arr_size && (arr1[i] + arr1[j]) > arr1[k])

           {

               k++;

           }

           ctrTriangle += k - j - 1;

       }

   }

   return ctrTriangle;

}

int main()

{

   int arr1[] = {7, 15, 6, 3, 11};

   int n = sizeof(arr1) / sizeof(arr1[0]);

   int i;

   printf("The given array is :  ");

   for (i = 0; i < n; i++)

   {

       printf("%d  ", arr1[i]);

   }

   printf("\n");

   printf("Number of possible triangles can be formed from the array is: %d\n",

          CountNumberOfTriangles(arr1, n));

   return 0;

}

OUTPUT:

The given array is :  7  15  6  3  11 

Number of possible triangles can be formed from the array is: 4

Related Topics

  • Integer x appears more than n by 2 times in sorted array

      Jan 15, 2022

  • Program to find majority element of an array

      Jan 03, 2022

  • Program to print a matrix in spiral form

      Jan 03, 2022

  • WAP to find the maximum circular sub array sum of given array

      Jan 03, 2022

  • WAP to find the number of times occurs a given number in an array

      Jan 03, 2022

  • Program to sort an array of 0s, 1s and 2s.

      Jun 30, 2021

  • Subscribe Now