C rand() library function

The function int rand(void); returns a pseudo random integer number between 0 and RAND_MAX. RAND_MAX is a constant defined in stdlib standard library, it's value is library dependent, but is guaranteed to be at least 32767. The function rand uses a seed to generate the series, which should be initialize using srand. If seed remains the same, then rand function generates same sequence of random numbers.

  • In range of 0 - N : rand() % N+1.
  • In range of 1 - N : (rand() % N) + 1.
  • In range of N - M : (rand() % M-N+1) + N.

Function prototype of rand

int rand(void);

Return value of rand

This function returns an integer between 0 and RAND_MAX.

C program using rand function

The following program shows the use of rand function to generate a sequence of pseudo random numbers.

#include <stdio.h>
#include <stdlib.h>

int main(){
    unsigned int seed;
    int n, counter;

    printf("Enter a unsigned number(seed)\n");
    scanf("%u", &seed);
    
    /* Initialize random number generator using srand */
    srand(seed);
    
    printf("Enter number of random numbers\n");
    scanf("%d", &n);
    for(counter=0; counter < n; counter++){
        printf("%d ", rand());
    }
    
    return 0;
}

Output
Enter a unsigned number(seed)
234
Enter number of random numbers
7
802 32478 7150 29924 30401 13148 15783