Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Generating Random Numbers

Generating Random Numbers


Video Summary: https://youtu.be/AT0P3FGt7qg


Sometimes, you will want to have random input for your program, such as if you were creating a game of luck or making sure your program won't crash with unexpected values. You can do this with the built in functionality and libraries for C++.

You can generate a "random" number simply by assigning a variable the value rand():

 
#include <iostream>
using namespace std;

int main(){
    int randomNum = rand();
    cout << randomNum;

    return 0;
}

However, there are two problems with this. First, the number will not be in any defined range and might not be useful to you. You may want to use the modulus operator '%' and use the remainder of some division. For example, if you wanted a number between 0 and 5, you would use % 6 (max value you want + 1):

 
#include <iostream>
using namespace std;

int main(){
    int randomNum = rand() % 6;
    cout << randomNum;

    return 0;
}

The second problem is that your number will not actually be random. Computers run on algorithms, which means they have a process of generating this number that will always result in the same output. If you don't want the same numbers every time, you could consider using a seed to modify the outputs using srand(seed_number).

 
#include <iostream>
using namespace std;

int main(){
    srand(2);
    int randomNum = rand() % 6;
    cout << randomNum;

    return 0;
}

But changing your seed every time you run the program is not ideal. To generate numbers you or a user would not be able to predict, you would want the seed to be something that is constantly changing. You could achieve this by using the time library, and using the computer's clock to generate the numbers. Since time is always changing, you will get different numbers each time you hit run, which provides essentially random numbers.

  1. include <time.h> at the top of your program
  2. use time(NULL) as your seed_number in srand

 
#include <iostream>
#include <time.h>
using namespace std;

int main(){
    srand(time(NULL));
    int randomNum = rand() % 6;
    cout << randomNum;

    return 0;
}

Exercise

Create a dice game that generates two random numbers, one for each player. You will need to use modulus and addition to make sure the numbers are between 1 and 6. Use a time seed so that the results vary every time you run the program. A sample output could look like this:

Player one rolled a 3
Player two rolled a 2

Solution