This value is converted to an unsigned integer and used as the seed to the random number generator. Function time takes NULL as an argument and it is found in the header time.h Now it is time for the final step in our dice rolling program is to randomize the numbers without having to enter the seed. The srand function in C seeds the pseudo random number generator used by the rand function. The seed for rand function is 1 by default. It means that if no srand is called before rand, the rand function behaves as if it was seeded with srand(1).
- The C Standard Library
- C Standard Library Resources
- C Programming Resources
- Selected Reading
Description
The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.
RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
Declaration
Following is the declaration for rand() function.
Parameters
NA
Return Value
This function returns an integer value between 0 and RAND_MAX.
Example
The following example shows the usage of rand() function.
Let us compile and run the above program that will produce the following result −
- Related Questions & Answers
- Selected Reading
Let us see how to generate random numbers using C++. Here we are generating a random numberin range 0 to some value. (In this program the max value is 100).
How To Generate Random Number In Dev C Download
To perform this operation we are using the srand() function. This is in the C library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand.
How To Generate Random Number In Dev C++ For Copy And Paste
The declaration of srand() is like below
It takes a parameter called seed. This is an integer value to be used as seed by the pseudo-randomnumber generator algorithm. This function returns nothing.
To get the number we need the rand() method. To get the number in range 0 to max, we are usingmodulus operator to get the remainder.
C++ Get Random Number
For the seed value we are providing the time(0) function result into the srand() function.