w3resource

C rand() function

C rand() function - Pseudo-random number generator

The rand() function is used to compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}]. The value of the {RAND_MAX} macro shall be at least 32767.

Syntax rand() function

int rand(void)

Parameters rand() function

NA

Return value from rand()

  • Returns a pseudo-random number.

Example: rand() function

The following example shows the usage of rand() function.

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   int n;
 
   for (n = 1;n <= 12; n++)
      printf("iteration %d, rand = %d\n", n, rand());
}

Output:

iteration 1, rand = 41
iteration 2, rand = 18467
iteration 3, rand = 6334
iteration 4, rand = 26500
iteration 5, rand = 19169
iteration 6, rand = 15724
iteration 7, rand = 11478
iteration 8, rand = 29358
iteration 9, rand = 26962
iteration 10, rand = 24464
iteration 11, rand = 5705
iteration 12, rand = 28145

The following example shows the usage of rand() function.

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   int range_min = -100;
   int range_max = 100;
   int n = 100000;
 
 for (int i = 0; i < n; i++)
    {
        // Note: This method of generating random numbers in a range isn't suitable for
        // applications that require high quality random numbers.
        // rand() has a small output range [0,32767], making it unsuitable for
        // generating random numbers across a large range using the code below.
        // The approach below also may result in a non-uniform distribution.
        // More robust random number functionality is available in the C++ <random> header.
        int r = ((double)rand() / RAND_MAX) * (range_max - range_min) + range_min;
        printf("  %6d\n", r);
    }
}

Output:

 ...
 ...
 59
 76
  8
-12
 64
 82
-93
 32
 62
 37
-51
-74
-93
-10
 72
-88
 -7
 68
 45
-85
-38
...
...
...
...

C Programming Code Editor:

Previous C Programming: C ldiv()
Next C Programming: C srand()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/stdlib/c-rand.php