C++ → Basics → Input → Arithmetic → Conditions → Loops → Array → Functions → Random Numbers
Random Numbers and Related Programs
- Random Numbers Basics (You are here)
- Dice Roll and Random Numbers
- Dice Roll, Sum and Counter
Learn how to generate uniformly distributed random numbers as integers and double in C Plus Plus. The following programs answer how to write a function in C++ that returns uniformly distributed random numbers.
The following C++ program will generate 10 random numbers from 0 to 9 as integers.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for (int a=0; a<10; a++)
{
int rnd = (int) (rand()%10);
cout << rnd << endl;
}
return 0;
}
Where, the for loop, for (int a=0; a<10; a++) runs 10 times. In this way we get 10 random numbers. The #include < cstdlib > header is for rand() function, and #include < ctime > header is for srand(time(0)) function, so that we can get different random numbers each time.
int rnd = (int) (rand()%10); Random Numbers between 0 and 9.
int rnd = (int) (rand()%21); Random Numbers between 0 and 20.
int rnd = (int) (rand()%7); Random Numbers between 0 and 6.
For example, the following program will generate Random Numbers between 0 and 6 (including 0 and 6).
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for (int a=0; a<10; a++)
{
int rnd = (int) (rand()%7);
cout << rnd << endl;
}
return 0;
}
How to generate uniformly distributed Random Numbers starting from 1 ??
Random Numbers between 1 and 10 (including 1 and 10)
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for (int a=0; a<10; a++)
{
int rnd = (int) (1+rand()%10);
cout << rnd << endl;
}
return 0;
}
Random Numbers as double
The following program will generate random numbers between 0 and 1 as double (0 is included but 1 is not).
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for (int a=0; a<10; a++)
{
double rnd = (double) (rand()%10/(double)10);
cout << rnd << endl;
}
return 0;
}
double rnd = (double) (rand()%10 generates random numbers from 0 to 9. And divided by 10 will convert them to decimals.