C - Library functions - Using srand() and rand()

Today a tiny tutorial to see how using srand() and rand() from the libc.

We will generate a number in a range between 0 and 2.
For that, we will use the functions:

  • time()
  • srand()
  • rand()
  • sleep()

The time() function because we want a random number that changes every second.
We will use it with the sleep() function.

We put a seed, generated by the time() function), into the srand() one.
Then we display this number with the rand() function.
And as we want a number between 0 and 2, we use the modulo operator (%).

Let's see it in details with this srand() / rand() example:

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#include <unistd.h>


int main (int argc, char *argv[])

{

  int seed;

  int i;


  i = 0;

  seed = time(NULL);

  srand(seed);

  while (i < 5)

  {

 sleep(1);

 printf("rand[%d]= %d\n", i, rand() % 3);

 ++i;

  }

  return 0;

}
Result:
Every second, we can see something like that:
 
 $ rand[0]= 2
 
You can now generate all random numbers you want. Well done. laugh
 

Comments

Comment: 

hii this solution is useful

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.