Random Number Generation

To generate random numbers, we first initialise the random number generator using seed. 

The C library function void srand(unsigned int seed) seeds the random number generator used by the function rand.

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

int main()
{
    srand(time(NULL));

    int a = rand() % 100;
    int b = rand() % 100;
    
    printf("The product of %d and  %d is %d", a, b, a*b);
    
    return 0;
}

Output:

1
The product of 96 and  14 is 1344

srand() prevents getting the consecutive series of random numbers that are exactly the same. This happens when the rand() is called inside the loop. 

Reference: 

SO link


Comments