- The C Standard Library
- C Library - Home
- C Library - <assert.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <float.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdarg.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <time.h>
- C Standard Library Resources
- C Library - Quick Guide
- C Library - Useful Resources
- C Library - Discussion
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C library function - rand()
Description
The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.
RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
Declaration
Following is the declaration for rand() function.
int rand(void)
Parameters
NA
Return Value
This function returns an integer value between 0 and RAND_MAX.
Example
The following example shows the usage of rand() function.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main () { int i, n; time_t t; n = 5; /* Intializes random number generator */ srand((unsigned) time(&t)); /* Print 5 random numbers from 0 to 49 */ for( i = 0 ; i < n ; i++ ) { printf("%d\n", rand() % 50); } return(0); }
Let us compile and run the above program that will produce the following result −
38 45 29 29 47
stdlib_h.htm
Advertisements
To Continue Learning Please Login
Login with Google