unique element in array in c

Certainly! Here's an example of finding the unique element in an array in C++:

#include <iostream>
using namespace std;

int findUnique(int arr[], int size) {
    int unique = arr[0];
    for (int i = 1; i < size; i++) {
        unique ^= arr[i];
    }
    return unique;
}

int main() {
    int arr[] = { 4, 2, 5, 2, 4 };
    int size = sizeof(arr) / sizeof(arr[0]);

    int uniqueElement = findUnique(arr, size);
    cout << "The unique element in the array is: " << uniqueElement << endl;

    return 0;
}

Explanation:

  1. findUnique function takes an array arr[] and its size size as arguments.
  2. It initializes unique with the first element of the array arr[0].
  3. It uses the bitwise XOR operator ^= inside a loop to find the unique element.
  4. The loop starts from index 1 and iterates through the array, performing XOR operations on each element with unique.
  5. The XOR operation (^) cancels out pairs of identical elements, leaving the unique element behind.
  6. The function returns the unique element.
  7. In main(), an array arr is defined with some values, and its size is calculated.
  8. findUnique is called with the array and size, and the result is printed out.

This code leverages bitwise XOR to find the unique element by canceling out the pairs of identical elements in the array.