Home > C > Generating Random Number in C

Generating Random Number in C

Generating random numbers is very important in programming. It’s difficult as much as it’s important. Actually, there is nothing random. A number, which is choosen according to some criterias (mostly time), is used in some functions, then a random number is given (for us) by those functions…
Let’s start.


Structure 1.1: We will need three libraries. (stdio.h,stdlib.h and time.h)

1
2
3
4
5
6
7
8
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main(){
srand((unsigned)time(0)); /* this function is used to generate a different number for each time we call rand() function  */
rand() % MaxNum; /* The MaxNum is our maximum limit. */
}

Formula: 0 <= result < MaxNum

Example 1.1: This using gives us a random number between 0(included) and 100(excepted).

1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main(){
srand((unsigned)time(0));
printf("The generated random number: %d",rand() % 100);
getch();
}

getch() function is used to see the result before the command screen closed and only exist on dos based operating systems. We could use the system(”pause”) function instead of it.


Don’t forget! In the cyber world, there is not random. I think, in the real world is too…

Bookmark and Share
Categories: C Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.
eXTReMe Tracker