Kah – The Developer

Generating random characters in C.

Posted by: kahgoh on: 21 July, 2008

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. Some people would use the modulus operator (“%”) to choose a number between 0 and 26 like this:

randNum = rand() % 26;

The problem with using this technique is that it is reliant on the fact that MAX_RAND is greater than 26 to get the full range of possible values. If it was not greater than 26, then you would not be able to get any random values between MAX_RAND and 26. By normalising dividing the random value by MAX_RAND + 1 and then multiplying by 26, you are do not need to worry about whether MAX_RAND is greater than 26.

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).

Tags:

1 Response to "Generating random characters in C."

Kah,

Good stuff.

I never want to go back to C/C++ after i have done C#.
C# is so much simpler. Keep us posted.

Leave a Reply