- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C library - rand() function
The C stdlib library rand() function is used to returns the pseudo-random number in the range of 0 to RAND_MAX.
RAND_MAX represents the maximum value that can be returned by the rand() function, and their default value may vary depending on the implementation of the c library. But it is granted to be at least 32767.
Syntax
Following is the C library syntax of the rand() function −
int rand(void)
Parameters
This function does not accepts any parameters.
Return Value
This function returns an integer value that is lies between 0 to RAND_MAX.
Example 1
In this example, we create a basic c program to demonstrate the use of rand() function.
#include <stdio.h>
#include <stdlib.h>
int main() {
// store the random value
int rand_value = rand();
// display the random value
printf("Random Value: %d\n", rand_value);
return 0;
}
Following is the output, −
Random Value: 1804289383
Example 2
The below c program used to display the random number within a range using the rand() function.
#include <stdio.h>
#include <stdlib.h>
int main() {
// display the random value
int i;
for(i=1; i<=5; i++)
{
printf("%d ", rand());
}
return 0;
}
Output
Following is the output −
1804289383 846930886 1681692777 1714636915 1957747793
Example 3
let's create another example, we are creating a C program to generate random numbers that will be multiples of 10.
#include <stdio.h>
#include <stdlib.h>
int main() {
// display the random value
int num = 10;
int i;
for(i=1; i<=6; i++)
{
printf("%d ", rand()%num);
}
return 0;
}
Output
Following is the output −
3 6 7 5 3 5