Previous Page
Next Page

rand

Obtains a random integer value

#include <stdlib.h>
int rand( void );

The rand( ) function returns a pseudorandom number between 0 and RAND_MAX. The symbolic constant RAND_MAX is defined in stdlib.h, and is equal to at least 32,767 (or 215 -1).

To initialize the pseud-random number generator, call the srand( ) function with a new seed value before the first call to rand( ). This step ensures that rand( ) provides a different sequence of random numbers each time the program runs. If you call rand( ) without having called srand( ), the result is the same as if you had called srand( ) with the argument value 1.

Example

printf( "Think of a number between one and twenty.\n"
        "Press Enter when you're ready." );
getchar( );

srand( (unsigned)time( NULL ) );

for ( int i = 0; i < 3; i++ )       // We get three guesses.
{
  printf( "Is it %u? (y or n) ", 1 + rand( ) % 20 );
  if ( tolower( getchar( ) ) == 'y' )
  {
    printf( "Ha! I knew it!\n" );
    exit( 0 );
  }
  getchar( );                        // Dicard newline character.
}
printf( "I give up.\n" );


Previous Page
Next Page