Home > Backend Development > C++ > body text

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

WBOY
Release: 2023-08-30 16:45:07
forward
1168 people have browsed it

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
Copy after login

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;
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!