Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use

 

Random Number Generator

Required headers: 

#include <stdlib.h>
#include <time.h>

Computers can be used to simulate the generation of random numbers with the use of the rand( ) function.  This random generation is referred to as a pseudo-random generation.  These created values are not truly "random" because a mathematical formula is used to generate the values.

rand( )   returns a random positive integer in the range from 0 to 32,767.  This function can be thought of as rolling a die with 32,767 faces.  The numbers are generated by a mathematical algorithm which when given a starting number (called the "seed"), always generates the same sequence of numbers.  Since the same sequence is generated each time the seed remains the same, the rand( ) function generates a pseudo-random sequence.  To prevent the same sequence from being generated each time, use
 srand(x) to change the seed value.

srand(x)  used to set the starting value (seed) for generating a sequence of pseudo-random integer values.  The srand(x) function sets the seed of the random number generator algorithm used by the function rand( ).  A seed value of 1 is the default setting yielding the same sequence of values as if srand(x) were not used.  Any other value for the seed produces a different sequence.

Using
srand(time(NULL));
makes use of the computer's internal clock to control the choice of the seed.  Since time is continually changing, the seed is forever changing.  Remember, if the seed number remains the same, the sequence of numbers will be repeated for each run of the program.

 

Generating random numbers within a specified range:
 
In order to produce random integer numbers within a specified range, you need to manipulate the rand( ) function. 
 The formula is:

int number = a + rand( ) % n;

a = the first number in your range
n = the number of terms in your range
(range computed by 
largest value - smallest value + 1)

 

 

Sample program:

/*generate 10 random numbers between 10 and 55 inclusive, without repetition of the sequence between program runs*/

#include <iostream.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    
// to prevent sequence repetition between runs     
     srand(time(NULL));  

  
     for(int i = 1; i <=10; i++)     // looping to print 10 numbers
     {
           cout<< 10 + rand( ) % 46;  
// formula for numbers 
    
}

     return 0;
}

 

 

<stdlib.h>
<time.h>

 

 

rand( ) requires header <stdlib.h>

 

 

 

 

srand(x) requires the header <stdlib.h>

 

 

srand(time(NULL));
requires both <stdlib.h> and <time.h>

 

 

 

 

Example:

/*random integers between 35 and 42 inclusive*/

int num =35+rand( )% 8;