[Solved] How does rand() work in C? [closed]


You should know that the easiest way to get information about the C standard library is by using manual pages on a Linux/UNIX system.

Manual chapter 3 is where you’ll find manual pages regarding the standard library. To get documentation for rand, type man 3 rand at a shell prompt.

In case you don’t have the manual pages handy, I’ll just quote from the description here:

DESCRIPTION

   The  rand()  function returns a pseudo-random integer in the range 0 to
   RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

   The srand() function sets its argument as the seed for a  new  sequence
   of  pseudo-random  integers  to be returned by rand().  These sequences
   are repeatable by calling srand() with the same seed value.

   If no seed value is provided,  the  rand()  function  is  automatically
   seeded with a value of 1.

   The function rand() is not reentrant or thread-safe, since it uses hid‐
   den state that is modified on each call.  This might just be  the  seed
   value to be used by the next call, or it might be something more elabo‐
   rate.  In order to get reproducible behavior in a threaded application,
   this  state must be made explicit; this can be done using the reentrant
   function rand_r().

   Like rand(), rand_r() returns a  pseudo-random  integer  in  the  range
   [0, RAND_MAX].  The seedp argument is a pointer to an unsigned int that
   is used to store state between calls.  If rand_r() is called  with  the
   same  initial value for the integer pointed to by seedp, and that value
   is not modified between calls, then  the  same  pseudo-random  sequence
   will result.

   The  value pointed to by the seedp argument of rand_r() provides only a
   very small amount of state, so this function will be a weak pseudo-ran‐
   dom generator.  Try drand48_r(3) instead.

RETURN VALUE

   The rand() and rand_r() functions return a value between 0 and RAND_MAX
   (inclusive).  The srand() function returns no value.

If you want to know how the code itself works, I can break it down for you:

#include <stdio.h>

Includes the standard I/O libraries. (needed in this case to get the definition of printf().)

#include <stdlib.h>

Includes the C standard library (for the current platform). This will be needed to get the definition of rand(), srand(), and time().

int main()

Defines the function main(), which will be sought out as the entry point for your compiled executable file at a later date.

{

Defines the scope of main().

   int i, n;

Allocates memory space on the stack for two int variables, i, and n.

   time_t t;

Allocates memory space on the stack for a time_t structure, which will be used later for the current time.

   n = 5;

Initializes int n to the value 5.

   /* Intializes random number generator */
   srand((unsigned) time(&t));

First calls time() with the argument being the memory address of the time_t allocated on the stack earlier. This will populate the time_t with the current time. (which is actually just expressed as an integer – the number of seconds since the “epoch” – see man 2 time)

Next, calls srand() with that value (after casting it to unsigned int, which presumably avoids a compiler warning, but is probably safe if you know that sizeof(time_t) >= sizeof(int).). Calling srand() here will seed the PRNG (pseudo-random number generator).

   /* Print 5 random numbers from 0 to 49 */
   for( i = 0 ; i < n ; i++ ) 
   {

In the for statement (in my own words), you’ll see <initialization-instruction> ; <condition> ; <loop-instruction>. The contents of the loop are executed while <condition> is true (which, in C terms, means non-zero, but that’s a separate discussion).

Set the int i defined earlier to zero. While i is less than n, do the operations within the curly braces ({ ... }), then increment i (++i) and check the condition again. (n was defined to be 5 earlier, so loop though the values [0, 1, 2, 3, 4])

      printf("%d\n", rand() % 50);

The printf() call uses format strings to print its output. The %d means you want printf to print out the first parameter assuming that it is an unsigned decimal integer. If you include more format strings in the printf call, you should include multiple corresponding parameters to the printf() function.

The \n, when it appears in a character or string constant, is a linefeed. So after the number is printed, the cursor will move to the beginning of the next line.

Finally, rand() % 50 means “call rand(), divide the result by 50, and then take the remainder”. (The % is the modulus operator, which means you want the remainder.) For example, if rand() returns 1000, you’ll get 0 printed to the screen, since 1000 % 50 == 0 (that is, 1000 divided by 50 equals 20, remainder 0).

So the end result will be printing a pseudo-random value between 0 and 49.

   }

   return(0);

This will cause main() to finish executing and return to its caller (probably whatever code loads binaries on your operating system). It will also most likely cause the exit status of your program to be 0.

}

0

solved How does rand() work in C? [closed]