Challenge 41

Description

The purpose of this challenge is to use arrays and functions.

Requirements

      1. Write a function void show_array(int array[], int size, char spacer = ‘\n’). This function will display each element of array using the character spacer to separate each element. The size parameter indicates the size of the array. Note that the 3rd parameter has a default value.
      2. Include <ctime> and <cstdlib> at the top of your code
      3. Write a function void fill_array(int array[], int size, int value). This function will fill the entire array passed in the array parameter, setting each element to value. 
      4. Write an overloaded function void fill_array(int array[], int size, int min, int max). This function will fill the entire array, setting each element to a random number between min and max.
      5. In the function in step 4, use the following code to generate a random number
        void fill_array(int array[], int size, int min, int max)
        {
            int value = min + (rand() % (max - min + 1));
        
            // at this point, value will be a random number between min and max
        }
        
      6. Write a function int count_value(int haystack[], int size, int needle). This function will count how many occurrences of needle are in the array passed in the haystack parameter. The return value of this function is the count.
      7. See the main() function given below

      DO NOT USE

      The vector class from the STL

      Sample main()

      int main()
      {
        int data1[30];
        int data2[10] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 };
        int data3[20];
      
        srand(time(NULL));          // needed for randomizing
      
        // fill entire array with the value 1
        fill_array(data1, 30, 1);
      
        // fill array with random numbers between 1 and 9
        fill_array(data3, 20, 1, 9);
        // show array - should show on one line automatically
        show_array(data1, 30, ' ');  // 3rd parameter is a space
      
        // show array - should show each element, one per line
        show_array(data3, 20);       // no 3rd parameter
        // showing the arrays above will allow you to confirm 
        // the counts below
      
        // should show 30 occurrences
        cout << "data1 has " << count_value(data1, 30, 1) << " occurrences " << endl;
      
        // should show 2 occurences
        cout << "data2 has " << count_value(data2, 10, 5) << " occurrences " << endl;
      
        // should show random number of occurrences, which you can 
        // confirm by counting the values in the output above
        cout << "data3 has " << count_value(data3, 20, 7) << " occurrences " << endl;
        return 0;
      }

      CATALOG ID: CPP-CHAL0041

Print Requirements