Count the number of possible triangles in C++


We are given an array which contains the length of sides of triangles. The goal is to find the number of possible triangles that can be made by taking any three sides from that array.

We will do this by checking if the sum of any two is always > third side. If yes these three sides can make a triangle. Increment count of possible triangles that can be made.

Let’s understand with examples.

Input − arr[]= {1,2,4,5}

Output − Count of possible triangles − 1

Explanation − Sides (2,4,5) can only make a triangle as 2+4>5 & 4+5>2 & 2+5>4

Input − arr[]= {4,5,6,3,2}

Output − Count of possible triangles − 7

Explanation − Sides (4,5,6), (4,5,2),(4,5,3),(4,3,2),(5,6,3),(5,6,2) can make triangles.

Approach used in the below program is as follows

  • We take an integer array arr[] initialized with random positive numbers.

  • Function countTriangles(int arr[], int n) takes array and its length and return possible triangles that can be made.

  • Take initial count of triangles as 0.

  • Take three for loops for three sides.

  • Outermost loop 0<=i<n-2, inner i<j<n-1 and innermost j<k<n

  • For sides arr[i],arr[j],arr[k] check if they form sides of triangle.

  • Check arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i] if true increment count.

  • Return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countTriangles(int arr[], int n){
   // Count of triangles
   int count = 0;
   for (int i = 0; i < n-2; i++){
      for (int j = i + 1; j < n-1; j++){
         for (int k = j + 1; k < n; k++){
            //any two sides have sum > third
            if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i])
               { count++; }
         }
      }
   }
   return count;
}
int main(){
   int Arr[] = { 1,2,5,3,6,8,10 };
   int len = sizeof(Arr) / sizeof(Arr[0]);
   cout << "count of Triangles possible : "<< countTriangles(Arr, len);
   return 0;
}

Output

If we run the above code it will generate the following output −

count of Triangles possible : 8

Updated on: 29-Aug-2020

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements