Generate random number in C/C++ programming language.
Generating Random number in C++:
We will use the rand() function from the cstdlib library. rand() will generate one random number for each call. we will get one random number between the 0 to RAND_MAX for each call. please look at the following code.
Program: Random number generator in C/C++:
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> #include <cstdlib> using namespace std; int main() { int i; for(i=0; i<5; i++){ cout << rand() <<endl; } return 0; } |
Output:
1 2 3 4 5 6 7 |
root@ubuntu:/home/venkatesh/Code/cpp/progs# g++ rand.cpp -std=c++11 root@ubuntu:/home/venkatesh/Code/cpp/progs# ./a.out 1804289383 846930886 1681692777 1714636915 1957747793 |
For example following rand function will generate one random value between the 0 to 100 for each call.
1 |
rand()%100; |
Ex2: following rand() function generates a number between the 1 to 100.
1 |
rand()%100 + 1; |
Here is the same program but in this case, it will generate a random number between the 1 to 100.
Program to generate the random numbers between the 1 to 100 :
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> #include <cstdlib> using namespace std; int main() { int i; for(i=0; i<5; i++){ cout << rand()%100+1 <<endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
root@ubuntu:/home/venkatesh/Code/cpp/progs# g++ rand.cpp -std=c++11 root@ubuntu:/home/venkatesh/Code/cpp/progs# ./a.out 84 87 78 16 94 root@ubuntu:/home/venkatesh/Code/cpp/progs# ./a.out 84 87 78 16 94 root@ubuntu:/home/venkatesh/Code/cpp/progs# |
To make our program to be a completely random number generator we need to use srand() function. srand function takes one argument seed.
Prototype of srand() function:
1 |
void srand(unsigned int seed); |
So we need to use different seed value each time we run the program. So the best solution to this is using
time() function from
ctime library. It will generate the number of seconds from Epoch.
So we can guarantee our program always receives the random seed number for
srand() function. So we will get random numbers whenever we call the
rand() function.
Random number generator program with srand and time functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int i; srand(static_cast<int>(time(0))); for(i=0; i<5; i++){ cout << rand()%100+1 <<endl; } return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
root@ubuntu:/home/venkatesh/Code/cpp/progs# g++ rand.cpp -std=c++11 root@ubuntu:/home/venkatesh/Code/cpp/progs# ./a.out 14 27 50 38 30 root@ubuntu:/home/venkatesh/Code/cpp/progs# ./a.out 41 19 8 15 2 root@ubuntu:/home/venkatesh/Code/cpp/progs# ./a.out 30 90 94 53 84 root@ubuntu:/home/venkatesh/Code/cpp/progs# |