In: Computer Science
In statistics, the mode of a set of values is the value that occurs most often or with the greatest frequency. Write a function that accepts as arguments the following:
The function should determine the mode of the array. That is, it
should determine which value in the array occurs most often. The
mode is the value the function should return. If the array has no
mode (none of the values occur more than once), the function should
return −1. (Assume the array will always contain nonnegative
values.)
Demonstrate your pointer prowess by using pointer notation instead
of array notation in this function.
can someone please help me with this in C++ programming language?
Thanks for the question. Below is the code you will be needing. Have used only pointers. Let me know if you have any doubts or if you need anything to change.
Thank You !
If you are satisfied with the solution, please rate the answer.
===========================================================================
#include <iostream>
using namespace std;
int mode(int* apointer, int size){
int max_occurence=0;
int modeNumber=0;
for(int i=0; i<size; i++) {
int current_occurence=0;
for(int j=0; j<size; j++
){
if(*(apointer+i)==*(apointer+j)){
current_occurence+=1;
}
}
if(current_occurence>max_occurence){
max_occurence=current_occurence;
modeNumber =
*(apointer+i);
}
}
if(max_occurence!=1) return modeNumber;
else return -1;
}
int main(){
int a[] =
{44,2,3,4,1,3,44,1,1,2,4,43,1,2,44,44,44};
cout<<"Mode =
"<<mode(a,sizeof(a)/sizeof(int));
cout<<endl;
int b[] = {1,2,3,4,5,6,7,8,9,10,11};
cout<<"Mode =
"<<mode(b,sizeof(b)/sizeof(int));
}
========================================================================