Home  >  Article  >  Backend Development  >  C/C++ program to find numbers that occur an odd number of times

C/C++ program to find numbers that occur an odd number of times

WBOY
WBOYforward
2023-08-30 16:45:071229browse

C/C++ program to find numbers that occur an odd number of times

A C program to find numbers that occur an odd number of times in a given array of positive integers. In this array, all numbers appear an even number of times.

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

Explanation

Use two loops, the outer loop traverses all elements one by one, and the inner loop counts the number of occurrences of the elements 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;
}

The above is the detailed content of C/C++ program to find numbers that occur an odd number of times. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete