Count number of triplets in an array having sum in the range [ a , b ] | C ++ program to count triplets with sum that lies in given range [ a , b ] . ; Function to count triplets ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int arr [ ] , int n , int a , int b ) { int ans = 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 ++ ) if ( arr [ i ] + arr [ j ] + arr [ k ] >= a && arr [ i ] + arr [ j ] + arr [ k ] <= b ) ans ++ ; } } return ans ; } int main ( ) { int arr [ ] = { 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int a = 8 , b = 16 ; cout << countTriplets ( arr , n , a , b ) << endl ; return 0 ; }