# Count of pairs (x, y) in an array such that x < y in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

We are given an integer array and the task is to count the total number of pairs (x, y) that can be formed using the given array values such that the integer value of x is less than y.

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

Output − Count of pairs (x, y) in an array such that x < y are − 6

Explanation

 X Y X < Y 2 4 true 2 3 true 2 1 false 4 3 false 4 1 false 4 2 false 3 2 false 1 2 true 3 4 true 1 4 true 3 1 false 1 3 false

## Approach used in the below program is as follows

• Input an array of integer elements to form an pair

• Calculate the size of an array pass the data to the function for further processing

• Create a temporary variable count to store the pairs having x less than y

• Start loop FOR from i to 0 till the size of an array

• Inside the loop, start another loop FOR from j to 0 till the size of an array

• Inside the loop, check IF arr[i] < arr[j] == TRUE then increment the count by 1

• Return the count

• Print the result

## Example

Live Demo

#include <iostream>
using namespace std;
int X_Less_Y(int arr[],int size){
int count = 0;
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
if (arr[i] < arr[j]){
count++;
}
}
}
return count;
}
int main(){
int arr[] = { 2, 4, 3, 1 };
int size = sizeof(arr) / sizeof(arr);
cout<<"Count of pairs (x, y) in an array such that x < y are: "<<X_Less_Y(arr, size);
return 0;
}

## Output

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

Count of pairs (x, y) in an array such that x < y are: 6