Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - rand()

C Library Function - rand()

C Standard Library - <stdlib.h> C Standard Library -

Description

C Library Function int rand(void) Returns a pseudo-random number between 0 and RAND_MAX inclusive.

RAND_MAX is a constant whose default value varies across implementations, but is at least 32767.

Declaration

The following is the declaration of the rand() function.



int rand(void)

Parameters

Return Value

This function returns an integer value between 0 and RAND_MAX.

Example

The following example demonstrates the use of the rand() function.

Example

#include

<

stdio.h

#include

<

stdlib.h

#include

<

time.h

int

main

(

)

{

int

i

,

n

;

time_t

t

;

n

=

5

;

/*

Initialize the random number generator

*/

srand

(

(

unsigned

)

time

(

&

t

)

)

;

/*

Output 5 random numbers between 0 and 49

*/

for

(

i

=

0

;

i

<

n

;

i

++

)

{

printf

(

"

%d

\

n

"

,

rand

(

)

%

50

)

;

}

return

(

0

)

;

}

Let's compile and run the above program, which will produce the following result:



38

45

29

29

47

C Standard Library - <stdlib.h> C Standard Library -