Random Numbers

To get different random numbers each time we run the program, we need to set the random number seed.

This is because random numbers use a starting number called the seed, and then apply a complicated formula to get each number after that.

Notice that we need to include ctime so that we can use the current system time as a starting point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Random numbers
#include<iostream>
#include <ctime>  //for the time to set the random number seed
using namespace std;
int main() {
  int num;
  srand((unsigned)time(0)); //to set random number seed
  num = rand(); //generates a random number
  cout << num << endl;
  num = rand(); //generates a random number
  cout << num << endl;
  num = rand(); //generates a random number
  cout << num << endl;
  system("pause");
  return 0;
}//main
CODE

Now we will get different values each time we run the program.

NEXT: A range of values