The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. 
Home Vectors Vector of Random Numbers  
Vector of Random Numbers
The first step is to generate a large number of random values and store them in a vector. By "large number," of course, I mean 20. It's always a good idea to start with a manageable number, to help with debugging, and then increase it later. The following function takes a single argument, the size of the vector. It allocates a new vector of ints, and fills it with random values between 0 and upperBound1. pvector<int> randomVector (int n, int upperBound) {pvector<int> vec (n); for (int i = 0; i<vec.length(); i++) { vec[i] = random () % upperBound; } return vec; }
for (int i = 0; i<vec.length(); i++) { cout << vec[i] << " "; } } Notice that it is legal to pass pvectors by reference. In fact it is quite common, since it makes it unnecessary to copy the vector. Since printVector does not modify the vector, we declare the parameter const. The following code generates a vector and outputs it: int numValues = 20;int upperBound = 10; pvector<int> vector = randomVector (numValues, upperBound); printVector (vector); On my machine the output is 3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6which is pretty randomlooking. Your results may differ. If these numbers are really random, we expect each digit to appear the same number of timestwice each. In fact, the number 6 appears five times, and the numbers 4 and 8 never appear at all. Do these results mean the values are not really uniform? It's hard to tell. With so few values, the chances are slim that we would get exactly what we expect. But as the number of values increases, the outcome should be more predictable. To test this theory, we'll write some programs that count the number of times each value appears, and then see what happens when we increase numValues.


Home Vectors Vector of Random Numbers 