Chapter Contents

Previous

Next
rand

rand



Simple Random Number Generation

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
PORTABILITY
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <stdlib.h>

int rand(void);


DESCRIPTION

rand returns pseudorandom numbers in the range from 0 to RAND_MAX . RAND_MAX is defined as 32767 in <stdlib.h> . The sequence of pseudorandom numbers is controlled by the value of seed . You can set this value by a call to srand . You can call srand at any time to reset the number generator to a new starting point. The initial default seed is 1.


RETURN VALUE

rand returns a random number between 0 and 32767.


PORTABILITY

The exact sequence of generated values for a particular seed and the exact range in which values can be generated may vary from implementation to implementation. (The sequence of numbers produced for a given seed by the library is the same as the usual UNIX C library implementation.)

The algorithm used for rand in this implementation is described in the ANSI Standard. The period is 232 calls. Because the value v returned is in the range 0 [le] v [le] 32767, individual values of v may be repeated after about 216 calls, but the sequence as a whole does not repeat until 232 calls.


EXAMPLE

#include <stdlib.h>
#include <stdio.h>

main()
{
   char card, suit;

      /* sets seed to 22                         */
   srand (22);

      /* Assign a random value to card and suit. */
   card = "A23456789TJQK"[rand()%13];
   suit = "CDHS"[rand()%4];

   printf("Your card: %c %c\n", card, suit);
}


RELATED FUNCTIONS

srand


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.