Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

*C++ Write a function called numOccurrences which accepts an array of integers,

ID: 645233 • Letter: #

Question

*C++

Write a function called

numOccurrences

which accepts an array of integers, its size, and

a value, and

returns the number of times that value appears in t

he array. Assume that all input values are valid (i

.e.

no error checking is needed on the array or its siz

e). Comments and proper indentation are required

for full marks.

For example, if an array of size 10 contained { 1,

2, 4, 2, 1, 2, 4, 3, 5, 4 }, then the value 2 occur

s 3

times. (Also, the value 1 occurs 2 times, the valu

e 5 occurs 1 time, and the value 7 occurs 0 times.)

*

Write a void function called

mostCommon

which accepts an array of integers and its size, a

nd

Explanation / Answer

#include <iostream>

using namespace std;

int numOccurrences(int arr[], int size, int value){
   int count = 0;
   for(int i = 0; i < size; ++i){
       if(arr[i] == value){
           count++;
       }
   }
   return count;
}

void mostCommon(int arr[], int size, int &value, int &times){
   int ind = -1;
   int max = -1;
   for(int i = 0; i < size; ++i){
       int temp = numOccurrences(arr, size, arr[i]);
       if(temp > max){
           max = temp;
           ind = i;
       }
   }
   times = max;
   value = arr[ind];
}

int main(){
   int arr[] = {1,2, 4, 2, 1, 2, 4, 3, 5, 4};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout << "Number of 2's is " << numOccurrences(arr, size, 2) << endl;
   int value, times;
   mostCommon(arr, size, value, times);
   cout << value << " occurs most number of times in the array. It's " << times << " times" << endl;
   return 0;
}