Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Expand Minimize

rand

Generates a pseudorandom number.

int rand( void );

Return Value

rand returns a pseudorandom number, as described above. There is no error return.

Remarks

The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. Use the srand function to seed the pseudorandom-number generator before calling rand.

Requirements

Routine Required header Compatibility
rand <stdlib.h> ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP

For additional compatibility information, see Compatibility in the Introduction.

Libraries

All versions of the C run-time libraries.

Example

// crt_rand.c
/* This program seeds the random-number generator
 * with the time, then displays 10 random integers.
 */

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

int main( void )
{
   int i;

   /* Seed the random-number generator with current time so that
    * the numbers will be different every time we run.
    */
   srand( (unsigned)time( NULL ) );

   /* Display 10 numbers. */
   for( i = 0;   i < 10;i++ )
      printf( "  %6d\n", rand() );
}

Sample Output

   19430
   28222
    9710
   12070
    7513
    9501
    1767
   26041
   11872
    4097

See Also

Floating-Point Support Routines | srand | Run-Time Routines and .NET Framework Equivalents

Show:
© 2015 Microsoft