4. However, the numbers generated by the rand() are not
random because it generates the same sequence each time
the code executed. So, if we run the code again, we'll get the
same sequence repeated as in the previous run.
5. To make a different sequence of numbers, we
should specify a seed as an argument to
a srand() function.
Eg: srand(98765);
To generate a ever changing sequence, we
need to feed something other than static
integer to the argument of
the srand() function.
6. The best solution is to seed the rand() function
using the current time as the argument
to srand(), by calling time() function from the
standard C++ library, <time.h>.
This returns the system time. Then, for
portability, we cast as an integer type:
eg : srand((int) time(0));
9. Generating a random number with a specified
range:
The rand( ) function by default generates a
number in range 0 to RAND_MAX. Now if you
want to generate a number with our own
specified range say 5 to 10, then you can change
the rand( ) as below:
(rand( ) % U) + L
(rand( ) % 10) + 5
or
random( U-L +1) + L
random(10-5+1) + 5
10. //Program to generate 5 random numbers in the range 5 - 14
//program is using randomize( ) and random( ) functions.
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
# include <time.h>
int main()
{
int num,i;
randomize();
for(i=0;i<5;++i)
{
num=random(14-5+1)+5 ; //num = random(U – L + 1) + L ;
cout<<num<<' ';
}
getch(); }
11. randomize ( ) function internally implements a macro that calls
time function of time.h. So, you need to use time.h header file in
your program to implement random ( ) function.