Generating random characters in C.

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>
5   int main(int argc, char *argv[])
6   {
7       char randChar = ‘ ‘;
8       int counter = 0;
9       int randNum = 0;
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));
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;
26          // Type cast to character to convert
27          // it to a char type.
28          randChar = (char) randNum;
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).


18 Responses to Generating random characters in C.

  1. Kwong Kiu says:


    Good stuff.

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

  2. jerome says:

    can you make me a program that randomize fixed numbers without getting the same number again coz im making a deal or no deal program in c.thanks.

    • kahgoh says:


      You should be able to adapt the above example to generate random numbers. If you don’t want the same number to repeat, your code would have to keep generating a random number until you get a different one, something like:

      int chooseNumber(int last)
          int result = last;
          while (result == last)
              result = 26 * (rand() / (RAND_MAX + 1.0));
          return result;

      Note though, I only wrote this off the top of my head and haven’t compiled and tried it out. This would only find a number different to the parameter value last.

    • maximrobi says:

      You could use the Fisher – Yates shuffle for that. It is very simple 🙂

  3. Michael says:

    Excuse . . . your coding is helping me a lots. . . how to store the random character (a-z) in the array ? and array can store 2 similar value ? like array[4]={1,1,2,2}

    • kahgoh says:

      The random number is changed to a random character at line 28. You already have an a variable that you can use as the array index (the variable is “counter” that is used in the for loop). So, all you should have to do is to change line 28 to store the random character into your array. In other words:

          char content[10];    // Array to hold content.
          content[counter] = (char) randNum;   // Change at line 28.

      And yes, an array can store repeated values.

      • Michael says:

        ya. . .the array can store repeated value . . . but how to limit that a array just can store two repeated value ? i mean that’s only two same value in the array ??

      • kahgoh says:

        Hmm, I’m not sure if I understand what you are after. I think you mean you want to restrict the values to just two possible values (like for example it can only pick “1” or “2” each time)? If so, then you need to modify lines 16 to 17, where the random number is chosen. The number 26 is used at this line since there are 26 letters in the alphabet. If you change this to just 2, it will restrict the range to 2 characters – either “a” or “b”. You can still load the characters into the array as in my previous comment.

  4. Michael says:

    i can’t give comment

  5. Michael says:

    Thanks for your help . . .

  6. Rahul says:


    Your code looks good. I have 3 questions:
    1. Are you trying to create 10 random characters and that you decide by using counter variable?

    2. Are you taking the value of RAND_MAX as the one defined in the C standard library i.e 0x7fff

    3. How does line 18 & 19 picks a number between 0-26. If you could take an example and show, it would be a great help.

    Your help is really appreciated 🙂

    • kahgoh says:


      1. Yes, it is creating 10 random characters.
      2. RAND_MAX as in how ever it is defined in the C library that you are using (the actual value may change, depending on your library).
      3. Not sure if I can explain it wel, but rand() picks a number between 0 and RAND_MAX (see In dividing the number by 1 + RAND_MAX, you get a number no higher than 1 (because RAND_MAX + 1 will always be greater than your chosen number). Multiply this random by 26, you will get a value no higher than 25 (because the number you are multiplying it with is always between 0 and 1). This technique for choosing random numbers between a certain range is also specified in that same page (

  7. Riccardo says:

    “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.”

    What you wrote is not true. The N * (rand() / (MAX_RAND + 1)) method versus rand() % N suffers similar problems if N > MAX_RAND, since the function will NOT be able to get to all possible values [0, N – 1]. The modulus version will only accumulate those inaccessible values toward the end of the interval, while the other will scatter the inaccessible values throught the accepted interval.

    To overcome this problem you would need to increase the density of your random numbers, for example by powering (rand() / MAX_RAND)^k or, more simply (rand()^k) % N of course at the price of modifying the statistics of your pseudorandom variable.

    However for the sake of clarity this is just fantasy since MAX_RAND may not be less than 32768 by C standards and it is often as bis as int limits therefore this problem in practice almost never exists.

  8. vasudha says:

    c program on how to generate random 100 characters with specifi gap between the words and also count no of palindromes in that 100 char sentence

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: