In this C program section, we will learn how to generate random numbers in C programming. Let us start with random numbers.
What is Randon Number?
We can define Random as something that happens without any conscious decision. Similarly, a random number is a number that is chosen unpredictably or randomly from the set of numbers.
During programming or creating a project, you may come through scenarios to generate numbers such as in dice games, lottery systems, etc. Although, there are in-built functions in C which makes it easy.
rand()
srand()
rand()
function
rand()
in c programming is a library function that generates random numbers within a range [0, RAND_MAX]. To use rand()
, we need to provide a header file <stdlib.h>
. The return type of rand()
is a random integer type.
Program: Generate the random numbers using the rand() function in C.
1 2 3 4 5 6 7 8 9 10 11 | #include <stdio.h> #include <stdlib.h> int main(void) { printf("Random number:: %d ", rand()); printf("\nRandom number:: %d ", rand()); printf("\nRandom number:: %d ", rand()); return 0; } |
Output:
Random number:: 1804289383
Random number:: 846930886
Random number:: 1681692777
Program: Generate 4 random numbers using the rand() function in C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <stdio.h> #include <stdlib.h> int main() { int i; printf("4 Random Numbers are: \n"); for (i=0; i<5; i++) { printf(" %d", rand()); } return 0; } |
Output 1:
4 Random Numbers are:
1804289383 846930886 1681692777 1714636915 1957747793
Output 2:
4 Random Numbers are:
1804289383 846930886 1681692777 1714636915 1957747793
No matter how many times you execute this program, it will return the same sequence of random numbers on every execution of the programming.
srand()
function
srand()
is a library function that sets the starting value for producing a series of pseudo-random integers. A srand()
function cannot be used without using a rand() function. The srand()
function is used to set the seed of the rand function to a different starting point.
It is used in the following manner in the programmer:
int srand(unsigned int seed)
Seed is an integer value for the new sequence in pseudo-random numbers.
Program: Generate the random numbers using the srand() function in C.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stdio.h> #include <stdlib.h> #include <time.h> //for time int main() { int num, i; printf("Enter how many numbers you want: "); scanf ("%d", &num); srand((unsigned) time (0)); // pass the srand() parameter printf("%d Random Numbers are:\n", num); // print within 0 to 100 for (i = 0; i <num; i++) { printf( "%d ", rand() % 100); } return 0; } |
Output:
Enter how many numbers you want: 5
5 Random Numbers are:
55 70 60 17 50
Again after second execution:
Enter how many numbers you want: 5
5 Random Numbers are:
36 70 91 3 2
Now you can see that the program returns series of different random number after every execution.