Program to find the most occurring element in an array of integers in C++

C++ program to find the most occurring element in an array of integers

Example:

Input: {12, 6, 4, 12, 9, 1}

Output: 12

# Algorithm

  1. Take the array as input from the user, along with the size of the array.
  2. Check if the array is empty or has only one element. If so, return an appropriate message.
  3. Initialize a variable max_count to 0.
  4. The outer loop picks all elements one by one.
  5. The inner loop finds the repetition of the picked element and compares it with the maximum so far. If the repetition is greater than the maximum, update the maximum count and the element that has the maximum count.
  6. After the inner loop completes, check if the maximum count is greater than 1. If so, print the element that has the maximum count.
  7. If the maximum count is not greater than 1, print a message indicating that there are no repeating elements in the array.

Code:

#include<bits/stdc++.h>
using namespace std;

void repeated_number(int arr[], int n) {
  int i, j, max_count = 0;
  cout << "\nMost occurred number: ";

  for (i = 0; i < n; i++) {
    int count = 1;
    for (j = i + 1; j < n; j++) {
      if (arr[i] == arr[j]) {
        count++;
      }
    }

    if (count > max_count) {
      max_count = count;
    }
  }

  // this loop checks if there are more than one elements that are repeated
  for (i = 0; i < n; i++) {
    int count = 1;
    for (j = i + 1; j < n; j++) {
      if (arr[i] == arr[j]) {
        count++;
      }
    }

    if (count == max_count) {
      cout << arr[i] << endl;
    }
  }
}

int main() {
  int arr[100], n, i;
  cout << "Enter number of elements: ";
  cin >> n;
  cout << "\nEnter array: ";
  for (i = 0; i < n; i++) {
    cin >> arr[i];
  }

  cout << "Original array: ";

  for (i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }

  repeated_number(arr, n);
  return 0;
}

Output

Enter number of elements: 5

Enter array: 2 3 2 4 2
Original array: 2 3 2 4 2

Most occurred number: 2

Time complexity: O(n2)

Program to find the most occurring element in an array of integers in C++