Count quadruplets with sum K from given array | C ++ program for the above approach ; Function to return the number of quadruplets with the given sum ; Initialize variables ; Initialize answer ; All possible first elements ; All possible second elements ; All possible third elements ; All possible fourth elements ; Increment counter by 1 if quadruplet sum is S ; Return the final count ; Driver Code ; Given array arr [ ] ; Given sum S ; Function Call
#include <iostream> NEW_LINE using namespace std ; int countSum ( int a [ ] , int n , int sum ) { int i , j , k , l ; int count = 0 ; for ( i = 0 ; i < n - 3 ; i ++ ) { for ( j = i + 1 ; j < n - 2 ; j ++ ) { for ( k = j + 1 ; k < n - 1 ; k ++ ) { for ( l = k + 1 ; l < n ; l ++ ) { if ( a [ i ] + a [ j ] + a [ k ] + a [ l ] == sum ) count ++ ; } } } } return count ; } int main ( ) { int arr [ ] = { 4 , 5 , 3 , 1 , 2 , 4 } ; int S = 13 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSum ( arr , N , S ) ; return 0 ; }