Random Number Generator in C

The ability for a program to generate random numbers is essential in many situations. Nearly every game has to do with random generation, such as a game that involves dice, go here for an example or any kind of card game, go here for an example. Random numbers are essential because how boring would it be if a game was always the same and predictable? Here is program coded in C that will generate a random number from 0 to 5.

//Full Working Program
#include <stdio.h>
#include <stdlib.h>//required to use 'rand()'
#include <time.h>//required to use 'srand(time(NULL))'

int main()
srand(time(NULL));//required for "randomness"

 int r;
 r=rand()%6;//generate a number between 0 and 5

return 0;


The algorithm to generate random numbers is actually very simple thanks to the 'rand()' function. However, before we can use this function we must declare the standard library header file.

#include <stdlib.h>

If we were to use try to use the 'rand()' function without declaring the pre processor directive '' then the compiler will complain.

#include <time.h>

The time header file is required to use 'srand(time(NULL))' this is because this function uses the clock on your computer to determine the "randomness" of your numbers. Every second the program will spit out a random number, if you were to not use the 'srand(time(NULL))' then the program will spit out the same number every time, try it for yourself!


Here the variable 'r' will equal a number from 0 to 5 if I were to put 8 instead of 6 then r would equal a number from 0 to 9. This is thanks to 'rand()' which randomly generates a number and then the modulus operator '%' spits out the remainder. What the modulus operator does is compute division and returns the remainder. For example if you had 10%4 the answer would be 2. This is because 4 goes into 10 twice with a remainder of 2.

So why will 'r' equal a number from 0 to 5? Remember 'rand()' computes a random number and the modulus returns a remainder so no matter what the number is as long as we divide it by 6 it can only have a remainder from 0 to 5, so say in one case that 'rand()' computes 13 that means 'r' would equal 13%6 and would thus equal 1. 14%6 equals 2, 15%6 equals 3, 16%6 equals 4, 17%6 equals 5, 18%6 equals 0 because there is no remainder, 19%6 equals 1, and now we are back to 1.

rand() % n//algorithm to generate a number from 0 to n-1

If we didn't want to generate a random number from 0 to 5, but 1 to 6 like rolling a piece of die. All we have to do is add 1 like so.

rand() % n+1//algorithm to generate a number from 1 to n