This is a C Program to find the odd element given an array with only two different elements.

This C Program finds odd element in a given array with only two different element.

Print the odd element with only two different elements in an array.

Here is source code of the C Program to find the odd element given an array with only two different element. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C Program to Find the Odd Element given an Array with only two Different Element */ #include <stdio.h> void printodd(int array[], int size) { int xor2 = array[0]; /* Will hold XOR of two odd occurring elements */ int set; int i; int n = size - 2; int x = 0, y = 0; /* The xor will basically be xor of two odd occurring elements */ for (i = 1; i < size; i++) xor2 = xor2 ^ array[i]; /* Get one set rightmost bit in the xor2. */ set = xor2 & ~(xor2 - 1); /* Now divide elements in two sets: */ for (i = 0; i < size; i++) { /* XOR of first set is finally going to hold one odd occurring number x */ if (array[i] & set) x = x ^ array[i]; /* XOR of second set is finally going to hold the other odd occurring number y */ else y = y ^ array[i]; } printf("\n The ODD elements are %d & %d ", x, y); } int main() { int array[] = {10, 3, 2, 10, 2, 8, 8, 7}; int arr_size = sizeof(array) / sizeof(array[0]); printodd(array, arr_size); getchar(); return 0; }

In this C Program, we have defined the array[] variable elements. Using ‘array_size’ variable compute the division of size of previous array value by the next value of array[] variable element.

The printodd() function is used to find the odd element given an array with only two different elements. The xor2 variable is used to hold XOR of two odd occurring elements. For loop is used to compute, the xor will basically be xor of two odd occurring elements.

Divide the elements in two sets, XOR of first set is finally going to hold one odd occurring number x. The XOR of second set is finally going to hold the other odd occurring number y.

$ cc pgm87.c $ a.out The ODD elements are 7 & 3

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

**Related Posts:**

- Practice BCA MCQs
- Apply for Computer Science Internship
- Check C Books
- Apply for C Internship
- Watch Advanced C Programming Videos