rand() — Generate random number
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
Format
#include <stdlib.h>
int rand(void);
General description
Generates a pseudo-random integer in the range 0 to RAND_MAX. Use the srand() function before calling rand() to set a seed for the random number generator. If you do not make a call to srand(), the default seed is 1.
Returned value
Returns the calculated value.
Example
CELEBR02
/* CELEBR02
This example prints the first 10 random numbers generated.
*/
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int x;
for (x = 1; x <= 10; x++)
printf("iteration %d, rand=%d\n", x, rand());
}
Output
iteration 1, rand=16838
iteration 2, rand=5758
iteration 3, rand=10113
iteration 4, rand=17515
iteration 5, rand=31051
iteration 6, rand=5627
iteration 7, rand=23010
iteration 8, rand=7419
iteration 9, rand=16212
iteration 10, rand=4086