I need to find the most occurring element in array C++. My code always returns 0.
p/s: This function should analyze the array to find the most occurring value in the array. You do not have to account for bi-modal occurrences, so the first modal value is enough to satisfy this function definition.
#include <iostream>
#include <ctime>
#include <random>
using namespace std;
int* generateArray(int size);
int findMode(int* arr, int size);
default_random_engine eng(static_cast<unsigned>(time(0)));
uniform_int_distribution<int>randNum(0,20);
int main()
{
// random 500 number for array coding
int SIZE = 20;
int* array = generateArray(SIZE); //output of 501 random element from 10-100
cout << endl;
findMode(array, SIZE);
delete[] array; //delete new int [size]
array = nullptr;
return 0;
}
int* generateArray(int size)
{
int* arr = new int[size];
cout << "Random number of 501 elements: " << endl;
cout << setw(6);
for (int i = 0; i < size; i++) //loop
{
arr[size] = randNum(eng);
cout << arr[size] << " ";
}
return arr; //return to array
}
int findMode(int* arr, int size)
{
int max_count = 0;
cout << "\nMost occurred number: ";
for (int i = 0; i < size; i++) {
int count = 1;
for (int j = i + 1; j < size; j++)
if (arr[i] == arr[j])
count++;
if (count > max_count)
max_count = count;
if (count == max_count)
cout << arr[i] << endl;
}
return 0;
}