In C, when you type cast an integer to a character, the character that is assigned is the ASCII character corresponding to that number. This property can be used to generate a set of random of characters, as follows:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4
5 int main(int argc, char *argv[])
6 {
7 char randChar = ‘ ‘;
8 int counter = 0;
9 int randNum = 0;
10
11 // Provide seed for the random number
12 // generator.
13 srand(time(NULL));
14 for (counter = 0; counter < 10; counter++)
15 {
16 // First, pick a number between 0 and
17 // 25.
18 randNum = 26 * (rand() / (RAND_MAX +
19 1.0));
20
21 // The ASCII code for ‘a’ is 97, so
22 // add 97 to the random number to get
23 // a lower case letter.
24 randNum = randNum + 97;
25
26 // Type cast to character to convert
27 // it to a char type.
28 randChar = (char) randNum;
29
30 printf (“Random char: %c\n“, randChar);
31 }
32 }
The documentation for rand() states that it returns a pseudorandom number between 0 and MAX_RAND. An alternative method is to use the modulus operator (“%”) to choose a number between 0 and 26 like this:
randNum = rand() % 26;
The difference between the two methods is that if the MAX_RAND was less than 26, the maximum number generated using the modulus operator will be, at most, MAX_RAND whereas the numbers will be more distributed using the first technique – although you still would not be able to get all possible numbers (thanks to Riccardo for the correction!).
Note that at line 13, the call to srand() provides a seed for the call to rand() later. If this seed was not provided, then the exact same sequence would be generated everytime. Also, if you also compile and run the example enough times, you should notice that the exact same sequence will appear after a number of tries. This is because rand is a pseudo random number generator (PRNG – see this wiki page for a detailed description).