
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count of Pairs (x, y) in an Array such that x < y in C++
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
#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[0]); 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