Answer to Question #212703 in C++ for moiz

Question #212703

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.


1
Expert's answer
2021-07-02T04:10:56-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS