By using the srand() and rand() functions contained in stdlib.h.
srand() seeds the random number generator with a value. If given the same seed, then rand() will return the same numbers in sequence. Usually, the time is used to seed the random number generator. So, for example:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
srand(time(NULL));
printf("A random number: %i\n", rand());
printf("A random number between 0 and 99: %i\n", rand()%100);
return 0;
}
Stepping through that, well.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
I think you probably know what these are. In this case, stdio.h is used for printf(), stdlib.h for srand() and rand(), time.h for time().
Code:
int main(int argc, char *argv[]) {
Standard main() function.
This calls srand() with the current time, as returned by the time() function. If you pass a pointer to time(), it will store the time in that variable. But because it additionally returns the time, you can seed the random number generator directly without using an additional variable.
Code:
printf("A random number: %i\n", rand());
printf("A random number between 0 and 99: %i\n", rand()%100);
The first simply prints out a randomly-generated number from the rand() function. This will be between 0 and (2^31)-1, probably not what you want. So, the second applies a modulus of 100 to the randomly-generated value. Modulus = remainder. Think of it as converting 1234 into 34, removing all but the tens and ones columns of a number. (If you use number%2, it will be 1 if number is odd, 0 if it's even.)
Terminate with a return code of 0, or success.
EDIT: dang, sean beat me to it :P