# Count pairs with Odd XOR 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 that can be formed using the given array values such that the XOR operation on the pairs will result in an ODD value.

The truth table for XOR operation is given below

 A B A XOR B 0 0 0 1 0 1 0 1 1 1 1 0

Input − int arr[] = {2, 8, 1, 5, 11}

Output − Count of pairs with Odd XOR are − 6

Explanation

 a1 a2 a1 XOR a2 2 8 10 2 1 3 2 5 7 2 11 9 8 1 9 8 5 13 8 11 3 1 5 4 1 11 10 5 11 14

## 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 formed with XOR operation as an odd value.

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

• Inside the loop, check IF arr[i] % 2 == FALSE then increment the even_XOR by 1 ELSE increment the odd_XOR++;

• Now set the count as odd_XOR * even_XOR

• Return the count

• Print the result

## Example

Live Demo

#include <iostream>
using namespace std;
//Count pairs with Odd XOR
int Odd_XOR(int arr[], int size){
int count = 0;
int odd_XOR = 0;
int even_XOR = 0;
for (int i = 0; i < size; i++){
if (arr[i] % 2 == 0){
even_XOR++;
}
else{
odd_XOR++;
}
}
count = odd_XOR * even_XOR;
return count;
}
int main(){
int arr[] = { 2, 6, 1, 4 };
int size = sizeof(arr) / sizeof(arr);
cout<<"Count of pairs with Odd XOR are: "<<Odd_XOR(arr, size);
return 0;
}

## Output

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

Count of pairs with Odd XOR are: 3