#include <iostream>
#include <ctime>
usingnamespace std;
//function prototypes
void displayArray(int numbers[], int numElements);
void displayRange(int numbers[], int numElements);
int getMiddle(int numbers[], int numElements);
int getHigh(int numbers[], int numElements);
int getLow(int numbers[], int numElements);
int main()
{
//declare array
int randNums[100] = {0};
int middleNums = 0;
int highNums = 0;
int lowNums = 0;
//initialize RNG
srand(static_cast<int>(time(0)));
//assign 100 random integers from 500 through 800 to the array
for (int sub = 0; sub <100; sub += 1)
randNums[sub] = 1 + rand() % (800 - 500 + 1);
//end for
//system("pause");
return 0;
}//end of main function
//*function definitions*
void displayArray(int numbers[], int numElements)
{
for (int sub = 0; sub < numElements; sub +=1)
cout<<numbers[sub]<<endl;
//end for
}//end of displayArray function
void displayRange(int number[], int numelements)
{
You should probably start by using non-random, hard coded arrays to test that your functions are working.
After that, you could either use a sort-and-search approach to be more efficient or a basic approach. I'm guessing from your assignment that you're not expected to use fancy algorithms.
The simplest solution is for each function to have a for loop that iterates over all the array elements, and keeps a running total of the number of elements that match a given condition. For example:
1 2 3 4 5 6 7
// Count the numbers in the array greater than 560
int count
for (int sub = 0; sub < numElements; ++sub)
{
if (numbers[sub] > 560)
++count;
}
Put a function in your toolkit in case you need to generate numbers in other ranges too:
1 2 3 4 5 6 7 8 9 10 11 12
int getRandInRange(int topOfRange, int bottomOfRange)
{
if(topOfRange < bottomOfRange)
{
int tempForSwap = topOfRange;
topOfRange = bottomOfRange;
bottomOfRange = tempForSwap;
}
int span = topOfRange - bottomOfRange + 1;
return (std::rand() % span) + bottomOfRange;
}
I should have restricted this to positive numbers. With a sufficiently large positive topOfRange and a sufficiently small (large negative) bottomOfRange, the subtraction step actually translates to an addition that causes an overflow, yielding the incorrect span. Sometimes this span is zero, resulting in a divide-by-zero error on the modulo calculation. getRandInRange(std::numeric_limits<int>::max(), std::numeric_limits<int>::min());
Caveat emptor!