Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

rand - Random number generator

&pagelevel(4)&pagelevel

Definition

#include <stdlib.h>

int rand(void);

rand returns a positive random integer in the range [0, 215-1].

A rand call selects values from a series of pseudo-random numbers by using a multipli-
cative, congruent random number generator. The generator has a period of 232.

Return val.

Note

Random number within [0, 215-1].

The random number generator can be initialized or reset with srand. If no initialization
takes place, the random number generator starts with its default value, like srand(1) does.

Example 1

Generate the same five random numbers twice:

#include <stdlib.h>
#include <stdio.h>
int i;
int main(void)
{
   for(i=1; i <= 10; ++i)
      {
        printf("%d\n", rand());
        if(i == 5)
          srand(1);
      }
   return 0;
}

Example 2

Simulation of rolling dice.

#include <stdio.h>
#include <stdlib.h>
#define A 32767              /* 2**15 - 1 */
int cpu_t;                   /* Query variable for CPU time*/
int i,x;
int main(void)
{
cpu_t = cputime(); 
srand(cpu_t);                /* Seed value for the random generator  */
for(i=1; i<= 6; ++i)         /* Simulation of six throws of a die    */
  {
  x =  rand()/(A/6)+1;       /* Determine random number in range 1-6 */
  printf("number thrown= %d\n",x);
  }
return 0;
}

See also

rand, srand