Random Number Generator in C
Here, you will get the program code to make a Random Number Generator in C programming. To generate a random number in c programming, we can use random function.
What is Random Number
Random number is a number that is generated by a process, that has no specific pattern or order.
What is the formula for random numbers
Random numbers in c, can be generated by using the rand() function. This random function is a built in function, which is defined in the <stdlib.h> header file. It returns a pseudo-random number between 0 and RAND_MAX.
int rand();
The rand() function returns a positive random number(between 0 to RAND_MAX).
Difference Between rand() and srand() functions
rand() | srand() |
● rand() is a function that generates a random number each time it is called. | ● The function srand() establishes the beginning point for producing a series of random integers. |
● It does not require any input parameter. | ● It requires a seed as an input parameter which is used to generate the random numbers. |
● It can be called any time in the program. | ● It is called only once in program to initialize the starting point value of seed. |
● It return random number, when called. | ● No return any value. |
● The seed can be provided using the time() function. |
Program #1. Random Number Generator in C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //Random Number Program in C #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { // Initialize random number generator srand(time(NULL)); // Generate random number int num = rand(); // Print the random number printf("\nRandom number: %d", num); return 0; } |
Output
Random number : 16582
Program #2 :- Generate 10 Random Numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //Generate 10 Random Numbers #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int i; srand(time(NULL)); printf("\nRandom numbers : "); for (i=1;i<10;i++) { printf(" %d", rand()); } return 0; } |
Output
Check out our other C programming Examples