C/C++ Program for Finding the Number Occurring Odd Number of Times?

CC++Server Side ProgrammingProgramming

A C++ program to find a number which occurs odd number of times in a given array of positive integers. In this array, all numbers occur even number of times.

Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7

Explanation

Use two loops in which the outer loop traversed all elements one by one and inner loop counts the number of occurrences of the element traversed by the outer loop.

Example

#include <iostream>
using namespace std;
int Odd(int arr[], int n){
   for (int i = 0; i < n; i++) {
      int ctr = 0;
      for (int j = 0; j < n; j++) {
         if (arr[i] == arr[j])
            ctr++;
      }
      if (ctr % 2 != 0)
         return arr[i];
   }
   return -1;
}
int main() {
   int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
   int n = 9;
   cout <<Odd(arr, n);
   return 0;
}
raja
Published on 20-Aug-2019 08:26:21
Advertisements