< C++ Programming < Code < Standard C Library < Functions

rand

Syntax
#include <cstdlib>
int rand( void );

The function rand() returns a pseudo-random integer between zero and RAND_MAX. An example:

srand( time(NULL) );
for( i = 0; i < 10; i++ )
  printf( "Random number #%d: %d\n", i, rand() );

The rand() function must be seeded before its first call with the srand() function - otherwise it will consistently return the same numbers when the program is restarted.

Related topics
srand
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.