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()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q