How to generate a random number in C++
This tutorial will see how to generate a random number in C++.
To generate random numbers rand()
function is used. This is a predefined function in the cstdlib
library. It generates random numbers and those numbers are in between 0 to RAND_MAX
.
RAND_MAX is the default maximum number and its value changes after every compilation. But the minimum value is set to 32767.
Once you call the rand() function it will generate a random number but, the same number will be generated for every execution.
To overcome this srand(unsigned int seed)
function is called. This is also a function from the cstdlib
library. It initializes the generator for random numbers. Due to this, the program generates different random numbers after every execution.
The argument seed is passed to the function which is the starting point for producing a random number.
C++ Code for Random Number generation
// C++ program to generate a random number #include <iostream> #include <cstdlib> using namespace std; int main() { cout << "The random values generated are :\n"; srand(time(0)); for (int i = 0; i < 5; i++) { cout << rand() << " "; } return 0; }
Output
First execution:
The random values generated are : 29601 26898 16499 23394 3789
Second Execution:
The random values generated are : 29640 24807 1493 17242 29260
The rand( ) function generates only random integers but you can get float random numbers by converting them to float.
(float)(element)
is an inbuilt method from C++ which converts the data type of an element to Float. Apply this function for random numbers and hence float numbers will be generated.
C++ program to generate random float numbers
#include <iostream> #include <cstdlib> using namespace std; int main() { cout << "The random float values generated are :\n"; srand(time(0)); for (int i = 0; i < 5; i++) { cout << (float)(rand()) / (float)(rand()) << " "; } return 0; }
Output
The random float values generated are : 1.29783 0.723817 223.661 0.200268 3.33896
Now if you want to generate the random numbers between some range then specify the lower and upper boundary and convert the generated random number by the rand( )
function within the specified range.
Refer to the following code for generating random numbers within some range.
Note: ‘%’ is an arithmetic operator used for modular division. It returns the remainder after the division operation is performed.
C++: Random Numbers with Range
//C++ program to generate a random number #include <iostream> #include <cstdlib> using namespace std; int main() { int min = 10; int max = 20; cout << "The random values generated in range 10 to 20 are :\n"; srand(time(0)); for (int i = 0; i < 5; i++) { cout << (rand() % (max - min + 1)) + min << " "; } return 0; }
Output
The random values generated in range 10 to 20 are : 14 19 12 19 10
Also, refer to Generate a random array in C or C++
Leave a Reply