Random Array

So i have to create an array with a random amount of numbers. I have the array working but only with a specific amount of numbers. How would i go about getting the array to be filled but with a random amount of random numbers? I also have to sort the array in ascending order and cant figure that out either.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  #include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;
int i;
int array[14];
int odd;
int Max;
int counter = 0;


int main()

{	
	cout << "The array consist of 14 numbers: ";
	cout << endl;

	srand ( time(0) );

	for (int j = 0;j<14;j++)
	{

		i = rand() % 101;
		 

		 if (i != i-1)
			array[j]=i;

		 else
		 {
			i = rand() % 101;
		 array[j]=i;
		 }
	}
	
	for (int k = 0; k < 14 ; k++)
	{
		cout << array[k] << " ";

	}
	cout << endl;
	
	getchar();
	return 0;
}
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.
Last edited on
Topic archived. No new replies allowed.