I am going to assume this is an assignment and you probably aren't allowed to use std::vectors or dynamic allocation, right?
If so, what you need to do is have your array allocate a "max size", but depending on what random length you want the array to be, you only use a subset of the array's first indices.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
// let's say, at most, we want there to be 300 elements.
const int Max_Num_Elements = 300;
int array[Max_Num_Elements ]; // sets the size of the array to 300
int actual_num_elements = 1 + rand() % (Max_Num_Elements);
// actual_num_elements will be a random number between 1 and 300.
// Now, use your array like normal, but pretend its size is only actual_num_elements instead of 300!
for (int j = 0; j < actual_num_elements; j++)
{
int rand_num = rand() % 101;
array[j] = rand_num;
}
// etc.
}
|
For sorting, it can get a bit tricky, but I would start small.
What if you only had two elements?
[4, 3] -> [3, 4]
How would you make sure these elements are always sorted?
Then, how would always make sure three elements are always sorted? [4, 5, 3] -> [3, 4, 5]
Four elements? [8, 4, 5, 3] -> [3, 4, 5, 8]
As you try to do this, you might pick up on a pattern. Hint: you'll probably want to use for loops and comparisons.