Hello, I am in a mid-level C++ course, but I'm pretty rusty with my basics. This course has asked that I create three void functions to:
a) initialize an array of 100 randomly-generated #s (range 1-30);
b) print that array;
c) find the mode(s) and display.
I managed to complete a) and b) with ease, but the crafting of c) has left me completely confused. A friend was helping, but it's been a while since he used C++. I'm supposed to use a second array to count the occurrences of the numbers. Here is the code I have so far:
insert
Code:
// This program generates a 100 element array of random numbers, displays that
// array, then finds the mode(or modes if more than one) and displays it.
#include <iostream>
#include <cstdlib> // For rand and srand.
#include <ctime> // For the time function.
#include <iomanip>
using namespace std;
void initialize(int[], int);
void print_array(int[], int);
void Mode(int[], const int, int[], const int);
const int ARRAY_SIZE = 100;
const int MAX_RANGE = 30;
int main()
{
int Array[ARRAY_SIZE]; //Create an array with 100 elements.
int second[MAX_RANGE] = {0}; //Create a secondary array for counting.
initialize(Array, ARRAY_SIZE);
print_array(Array, ARRAY_SIZE);
Mode(Array, ARRAY_SIZE, second, MAX_RANGE);
return 0;
}
void initialize(int nums[], int size)
{
// Get the system time.
unsigned seed = time(0);
// Seed the random number generator.
srand(seed);
// Loop to fill the array with random numbers from 1 to 30.
for (int index = 0; index < size; index++)
{
//Generate random numbers from 1 to 30.
nums[index] = 1 + rand() % MAX_RANGE;
}
}
void print_array(int nums[], int size)
{
for (int x = 0; x < size; x++)
{
if (x % 10 == 0) // At the end of ten elements, begin a new line.
cout << endl;
cout << setw(2) << nums[x] << " ";
}
cout << endl << endl;
}
void Mode(int nums[], int size, int secondary[], int size2)
{
//Create a counter array to store occurrences of items in first array.
int max = 0;
for(int i = 0; i < size; i++)
{
secondary[nums[i]]++;
if(secondary[nums[i]] > max)
max = secondary[nums[i]];
}
for(int i = 0; i <= size2; i++)
{
if(secondary[nums[i]] == max)
cout << "The mode is: " << secondary[i] << endl;
}
}