Q:

write a c++ program to find the most occurring number and how many times it occurs in the following example of array

0

write a c++ program to find the most occurring number and how many times it occurs in the following example of array.

int x[]={3,12,8,15,9,22,23,8};

The output:

the number most repeated is : 8 and it occurs 2 times

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <bits/stdc++.h>

using namespace std;

int max_count=0;
int mostFrequent(int arr[], int n)
{
	// Sort the array
	sort(arr, arr + n);

	// find the max frequency using linear traversal
	max_count = 1;
	int res = arr[0], curr_count = 1;
	for (int i = 1; i < n; i++) {
		if (arr[i] == arr[i - 1])
			curr_count++;
		else {
			if (curr_count > max_count) {
				max_count = curr_count;
				res = arr[i - 1];
			}
			curr_count = 1;
		}
	}

	// If last element is most frequent
	if (curr_count > max_count)
	{
		max_count = curr_count;
		res = arr[n - 1];
	}

	return res;
}
// driver program
int main()
{
	int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
	int n = sizeof(arr) / sizeof(arr[0]);
	cout <<"the number most repeated is : "<< mostFrequent(arr, n)<<" and it occurs "<<max_count<<" times";
	return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now