**C Random Number Generation**

**Disclaimer:**

First and foremost I am aware there is an alternative tutorial similar to this one. The tutorial is called, "Producing Random Numbers" by Jessehk. I understand the tutorial is useful and I am thankful they contributed to Dream in Code. However, I find the tutorial to be a little lacking (no disrespect intended). I hope this tutorial can add more to the topic and give users more information. I was unable to find more tutorials concerning random numbers. I hope this tutorial will be useful!

**What's an RNG?**

An RNG is a Random Number Generator. Essentially, the job of an RNG is to produce a random number. It is worth noting "random" is actually pseudo-random. True random does not exist, but we can make pretty nifty RNGs. In order to produce a seemingly random number we need to 'seed' the RNG.

A seed is value which initializes the RNG. If you don't have a unique seed then the "random" sequence will always be the same! This tutorial will use a common method to maintain a unique random sequence every time the program is ran. However, there are better methods. Those methods are more advanced and in general most programmers don't need such random numbers. If you are doing encryption or other sensitive coding you may need a better seed.

**What is an RNG used for?**

Random numbers are used all over the place. A common use of random numbers is within games. For example-- you may want to spawn a random number of enemies or produce loot at a random rate. In those cases you are going to need a random number. Another common use is in encryption, but that is rather advanced. My favorite use of random numbers is within algorithms. If you look closely you can find random numbers everywhere and learning how to generate them is useful. To learn more about RNGs give this a read.

**What do we need?**

For this tutorial I am going to use C's functions. In particular we will be using these functions:

srand()

rand()

time()

Finally, we will make use of the modulus operator. In C modulus is done by using the % operator. In order to use the functions we will need to include the proper header files.

The functions srand and rand are located in the stdlib.h header file. The time function is located in the time.h standard header file. In short, our includes will look like such:

#include <stdio.h> #include <stdlib.h> #include <time.h>

The stdio.h library will be used for printf. We will want to print out some random numbers and make sure our functions are working.

**Wait... modulus?**

I will take a moment to explain how to use the mod operator. The mod operation is sometimes called the remainder operation. In essence, mod is a lot like doing plain old division but we only care about the remainder left over after the division.

For example, if I asked you what 10 divided by 5 was you would easily answer, "2" because 5 goes into 10 two times. If I asked you what 10 mod 5 was, you need to do the division and look at what is left over. Because 5 goes into 10 two times there is nothing left over and therefore the result of 10 mod 5 is 0. Now let's look at another example where there is a remainder.

If we look at 10 divided by 3... in plain old division we would think 3 goes into 10 three different times but there is a remainder. If we look at 10 mod 3 we can easily tell what the result of this is. We know 3 goes into 10 three times and 1 is remaining. Therefore, 10 mod 3 is 1.

Why do we care? We will use mod to limit our output. A number can be huge.. infinite! In order to make our number stay bound within a range we need to use mod.

**Getting started**

The rand() function returns a random number. The range of possible values is large and depends on your system and what it can handle.

Let's make a function which returns a random number.

#include <stdio.h> #include <stdlib.h> #include <time.h> int getRandomNumber(void) { return rand(); } int main(void) { printf("%d\n", getRandomNumber()); return 0; }

When getting the output of this I got 1804289383. If you re-run you will notice you are getting the same random values. That feels pretty silly doesn't it? This is because we didn't seed rand(). Let's take a moment to seed it.

We will use srand and a unique seed. Where do we use srand? Well, we need to use it in a function that isn't where we plan to call rand. In this case we can use the main function because our self-made functions will be where we call rand.

What about our seed? Well, the most common technique is to use the current time in seconds. This is useful because time is always changing and gives us a unique output each time we run the program. We will seed via this, "srand(time(NULL));" without quotes. The NULL doesn't allow time to save the output in memory which is a plus-- because of security concerns. That isn't a concern to us now.

#include <stdio.h> #include <stdlib.h> #include <time.h> int getRandomNumber(void) { return rand(); } int main(void) { srand(time(NULL)); printf("%d\n", getRandomNumber()); return 0; }

Now we have a nice seed and a function which returns a random number. We are doing good but the range of random numbers is huge. Let's make a function which takes 2 arguments-- the base and the limit. We want to get a random number between the base and the limit (including the base and the limit). This is where mod is going to be useful.

#include <stdio.h> #include <stdlib.h> #include <time.h> int getRandomNumber(void) { return rand(); } int getRandomNumberRanged(int base, int limit) { return rand() % (limit - base + 1) + base; } int main(void) { srand(time(NULL)); printf("%d\n", getRandomNumberRanged(0, 10)); return 0; }

There we go-- we have a useful function for producing a random number within a given range. If you don't understand the mod involved and the use of a limit and a base try to work it out on a sheet of paper.

**So what can we do with this?**

Well-- I figure now you may be pondering that question. I have put together a real simple program to display a random number being used. In this case we use a random value to represent the sides of a coin. We can then use this program to randomly flip a coin and tell us where it lands.

In addition to putting together this small program I have cleaned up the code and added comments. Also be warned I changed the name of the ranged function and removed the old version.

/** * @title: Heads or Tails * @author: Stackoverflow * * @description: Simulates a coin toss * **/ #include <stdio.h> #include <stdlib.h> #include <time.h> #define HEADS 1 #define TAILS 0 /** * getRandomNumber - returns a random number within a bounded range * @base: the lowest possible number * @limit: the highest possible number * @return: an integer within the bounded range is returned **/ int getRandomNumber(int base, int limit); int main(void) { srand(time(NULL)); if (getRandomNumber(0, 1) == HEADS){ printf("Heads!\n"); } else { printf("Tails!\n"); } return 0; } int getRandomNumber(int base, int limit) { return rand() % (limit - base + 1) + base; }

**Conclusion**

I enjoyed writing this and I hope it helps people. Random numbers can be a lot of fun and they are not as complicated as they seem.

**Exercise**

A good exercise for using an RNG is to make a guessing game. The most common game is the guess-a-number game. The user must guess the number and if they are wrong the game will give the user a couple more tries. If the user can't guess in a couple tries the program should notify the user they lost and tell the user the number which was generated. I believe this is a good exercise and I leave it up to you to do!