In c++ Mode Function In statistics, the mode of a set of values is the value tha
ID: 3769683 • Letter: I
Question
In c++ Mode Function 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: A) An array of integers B) An integer that indicates the number of elements in the array 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 func- tion 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.
Explanation / Answer
#include <iostream>
#include <stdlib.h>
using namespace std;
int findMode(int *data,int size)
{
if(size == 0) //if no element is present then return -1 "base case"
return -1;
int i,j,mode,frequency=0,count = 0;
//dynamic allocation to the pointer [2D pointer]
int **freq_array = (int**)malloc(2*sizeof(int*));
for(i=0;i<2;i++)
freq_array[i] = (int*)malloc(size*sizeof(int));
/*
freq_array 1st row contains unique elements from array "data" and
its 2nd row contains its frequency count i.e. how many times
did it appear in array "data"
*/
for(i=0;i<size;i++)
freq_array[1][i] = 0;
for(i=0;i<size;i++)
{
for(j=0;j<count;j++)
if(freq_array[0][j]==data[i])
{
freq_array[1][j]++;
break;
}
if(j==count)
{
freq_array[0][count] = data[i];
freq_array[1][count] = 1;
count++;
}
}
//now finding the max. frequency of elements
for(i=0;i<count;i++)
if(freq_array[1][i]>frequency)
{
mode = freq_array[0][i];
frequency = freq_array[1][i];
}
//deallocating memory space
for(i=0;i<2;i++)
free(freq_array[i]);
if(frequency == 1)
return -1;
else
return mode;
}
int main()
{
int n,i,result;
cout<<"Enter size of array ";
cin>>n;
int data[n];
for(i=0;i<n;i++)
cin>>data[i];
result = findMode(data,n);
if(result == -1)
cout<<"Mode not found ";
else
cout<<"Mode is "<<result<<endl;
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.