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:
findUnique
function takes an arrayarr[]
and its sizesize
as arguments.- It initializes
unique
with the first element of the arrayarr[0]
. - It uses the bitwise XOR operator
^=
inside a loop to find the unique element. - The loop starts from index 1 and iterates through the array, performing XOR operations on each element with
unique
. - The XOR operation (
^
) cancels out pairs of identical elements, leaving the unique element behind. - The function returns the unique element.
- In
main()
, an arrayarr
is defined with some values, and its size is calculated. 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.