Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,240 questions

56,143 answers

573 users

How to count the triangles that can be formed using three different elements of an array in C++

1 Answer

0 votes
#include <iostream>
 
int GetNumberOfTriangles(int arr[], int size) {
    int count = 0;
 
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            for (int k = j + 1; k < size; k++) 
                // triangle = sum of two sides > value of the third side
                if (arr[i] + arr[j] > arr[k] &&
                    arr[i] + arr[k] > arr[j] &&
                    arr[k] + arr[j] > arr[i]) {
                    std::cout << arr[i] << " " << arr[j] << " " << arr[k] << "\n";
                    count++;
                }
        }
    }
    return count;
}
 
int main()
{
    int arr[] = { 2, 3, 4, 5, 6, 7 };
     
    int size = sizeof(arr) / sizeof(arr[0]);
     
    std::cout << GetNumberOfTriangles(arr, size);
}
 
 
 
 
/*
run:
 
2 3 4
2 4 5
2 5 6
2 6 7
3 4 5
3 4 6
3 5 6
3 5 7
3 6 7
4 5 6
4 5 7
4 6 7
5 6 7
13
 
*/

 



answered Sep 10, 2022 by avibootz
edited Sep 12, 2022 by avibootz
...