How is the ‘rand’ function used in C++?
In C++, the rand() function is used to generate a pseudo-random number. Its usage is as follows:
- Firstly, we need to include the header file
. - The rand() function can be called to generate a pseudorandom integer within the range of 0 to RAND_MAX. RAND_MAX is a macro that represents the maximum random number that the rand() function can generate.
- To generate a random number within a specific range, you can use the modulo operation. For example, to generate a random integer between 1 and 100, you can use rand() % 100 + 1.
- To generate a different random number sequence each time the program is executed, you can call the srand() function and pass a seed value as a parameter. Typically, you can use the current time as the seed value, such as srand(time(0)).