C Random Numbers
Random Numbers
In C, you can make random numbers with the rand()
function, which is found in the <stdlib.h>
library.
By default, rand()
gives the same sequence of numbers each time you run the program.
To get different results on every run, you can also use srand()
to set a "starting point" (called a seed).
Since you just learned about date and time, you can now use the current time as the seed (because it is always changing).
For this, you include <time.h>
in your program.
Basic Random Number
The function rand()
returns a random integer.
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int r = rand();
printf("%d\n", r);
return 0;
}
Note: If you run this program several times, you will see the same numbers each time. This is because we have not set a seed yet.
Seeding the Random Generator
To get different numbers every time you run the program, you must give rand()
a starting point (seed).
You do this with srand()
. A common trick is to use the
current time as the seed, because the time is always changing:
Example
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // seed with current time
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
Tip: Call srand()
only once, at the start of main
. Do not call it again inside a loop.
Random Number in a Range
Often you want numbers in a smaller range, like 0 to 9.
You can do this by using the modulo operator %
:
Example
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int x = rand() % 10; // 0..9
printf("%d\n", x);
return 0;
}
Real-Life Example: Rolling Dice
A common real-life use of random numbers is rolling a six-sided dice.
We can simulate this by using rand() % 6
to get numbers from 0 to 5, and then add 1 to make the range 1 to 6:
Example
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int dice1 = (rand() % 6) + 1;
int dice2 = (rand() % 6) + 1;
printf("You rolled %d and %d (total = %d)\n", dice1, dice2, dice1 + dice2);
return 0;
}
Each time you run the program, you will get two random numbers between 1 and 6, just like rolling two dice in real life.