![The C Standard Library Reference](/c_standard_library/images/c-mini-logo.jpg)
- The C Standard Library
- 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 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 - srand() function
The C stdlib library srand() function is used to initialize or sets the seed for the 'rand()' function, allowing us to generate different sequence of the random number. By default the seed value is 1 for the rand() function.
Syntax
Following is the C library syntax of the srand() function −
void srand(unsigned int seed)
Parameters
This function accepts a single parameter −
seed − It is an unsigned integer that represents the seed value.
Return Value
This function does not returns any value.
Example 1
Let's create a basic c program to demonstrate the use of srand() function.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { // Set seed based on current time srand(time(NULL)); int i; for (i = 0; i < 10; i++) { int value = rand(); printf("%d ", value); } return 0; }
Output
Following is the output, which always display random number −
22673 30012 9907 5463 13311 32059 17185 6421 15090 23066
Example 2
The below is the another example, we will generate random numbers within a specific range. Using srand() and srandrand() functions.
#include <stdlib.h> #include <stdio.h> #include <time.h> int main() { // Lower bound int lb = 20; // Upper bound int ub = 100; // Initialize random seed based on current time srand(time(NULL)); int i; for (i = 0; i < 5; i++) { // Generate a random number between lb and ub (inclusive) printf("%d ", (rand() % (ub - lb + 1)) + lb ); } return 0; }
Output
Following is the output, which always display random number −
44 77 70 86 75