rand
int  rand ( void );
stdlib.h
  cplusplus.com  

Generate random number.
  Returns a pseudo-random number in the range from 0 to RAND_MAX constant. This is generated by an algorithm that returns a series of non-related numbers each time is called. This algorithm should be initialized to different starting points using function srand to generate more realistic random numbers.
  RAND_MAX is a constant defined in stdlib.h. Its default value is implementation defined.

Parameters.

(none)
 

Return Value.
  An integer value between 0 and RAND_MAX.

Portability.
  Defined in ANSI-C.

Example.

/* rand example */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main ()
{
  /* initialize random generator */
  srand ( time(NULL) );

  /* generate some random numbers */
  printf ("A number between 0 and RAND_MAX (%d): %d\n", RAND_MAX, rand());
  printf ("A number between 0 and 100: %d\n", rand()%100);
  printf ("A number between 20 and 30: %d\n", rand()%10+20);

  return 0;
}
A good way to generate true random numbers is to initialize the random algorithm using srand with the current time in seconds as parameter obtained from time function included in <time.h>.
Output:
A number between 0 and RAND_MAX (32767): 30159
A number between 0 and 100: 72
A number between 20 and 30: 23

See also.
  srand


© The C++ Resources Network, 2000