How do we get a random number?
C provides a function to generate a random number, called rand(). The prototype is in <stdlib.h>. So make sure you have #include<stdlib.h>
int rand(void);
It is given nothing (that's what void means), and returns a random integer. Unfortunately, the number is in the range 0 to the maximum positive integer we can represent (about 2 billion).
How do we use it?
int x;
x = rand();
/* x now holds a random number between 0 and 2 billion */
How do we limit the range to be from 0 to 9?
Well, the modulus (%) operator can help us can help do that by
int x;
x = rand()%10 //this results in random numbers between 0 and 9
Could we use this code above to generate numbers from 10-19?
we can add 10 to all the numbers in the above code to accomplish this.
int x;
x = rand()%10 +10;
Let's break this down.
int pick (int start, int stop){
int y = (rand()%(stop - start+1))+start;
return y;
}
It turns out that if you use rand() with seeding properly, you're likely to get the same random number over and over. To do this, we have to use the time.h library as well as the srand() function.
To properly seed random, you can use the following code. This only needs to be done once when your code start.
#include<stdlib.h>
#include<time.h>
int main(){
srand(time(0)); //This line seeds the rand() function
}