In C++, as well as any other programming language, you can generate a random number or sequence of random numbers. Here, it involves the use of two libraries of C++, <cstdlib> as well as <ctime>.
New libraries
As mentioned, you need to include two new libraries in order for you to generate a random number. Here is some information about them:
Random Functions
All random numbers are called pseudo-random. This means that they are part of a predefined set of numbers in the language. In order for you to mix up the set each time you run a program, you need to seed the generator by making use of the srand() function.
Here is the definition of srand() and it's use:
Now that we know how to set up the generator, we can physically generate a number by making use of the rand() function.
Here is the definition rand() and it's use:
Here is an example program that will fill an array with random numbers:
Example 1:
Random array
Download source code here (Right click - Save Target As...)
The program simply places random numbers from 1 to 10 inside the array called arr. It will output the values in the array in the second program. This is a simple program to see how random numbers work. Run the program multiple times to see the different numbers appear.
Example 2:
Random Counter
Download source code here (Right click - Save Target As...)
This program will keep track of how many times a random number was drawn. This will increment the appropriate place in the array. The generated number itself will be the index of the array. One possible output can be:
The output will be different each time the program is run.
Example 3:
Random Stars
Download source code here (Right click - Save Target As...)
The program will simply output rows of stars to the screen 25 times. However, you may not see 25 rows since the inner loop will strictly be less than the generated number. If the random number is 0, the loop will not run and leave a blank row.
One possible output is this:
Another possible output is this:
I'm sure you get the picture. Each time you run the program, the output will be different.