Write a generic function common() that calculates the double of each element in the array and returns the value which is most frequent in an array. The function arguments should be the address of the array and its size. Make this function into a template so it will work with an array of any data type i.e. int, long, double.
#include <iostream>
using namespace std;
template<typename type>
type common(type *arr, int size){
int max_freq = 0, freq = 0;
type most_element, temp_most;
for(int i = 0; i < size; i++){
freq = 0;
arr[i] *= 2;
for(int j = 0; j < size; j++){
if(arr[i] == arr[j]){
freq++;
}
}
if(freq > max_freq){
max_freq = freq;
most_element = arr[i];
}
}
return most_element;
}
int main(){
int arr[5] = {1, 2, 1, 52, 1};
cout<<common<int>(arr, 5);
return 0;
}
Comments
Leave a comment