Random Numbers
1. Introduction
Random numbers are numbers generated in such a way that they appear to have no specific pattern. In C programming, random numbers are commonly used in applications such as:
-
Games (dice, cards, guessing games)
-
Simulations
-
Password generation
-
Statistical and scientific programs
C provides built-in functions to generate random numbers using the stdlib.h header file.
2. Header File for Random Numbers
To generate random numbers in C, the following header file is used:
For better randomness, we also use:
3. The rand() Function
Description
-
rand()generates a pseudo-random integer -
The number generated is between 0 and RAND_MAX
-
RAND_MAXis a constant defined instdlib.h
Syntax
Example Program
Limitation
-
Generates the same sequence each time the program runs
4. The srand() Function (Seed Function)
Description
-
srand()sets the seed value forrand() -
Seed controls the randomness of numbers
-
Using different seeds produces different sequences
Syntax
5. Using time() as Seed
To generate different random numbers every time, time(NULL) is used as seed.
Example
6. Generating Random Numbers in a Range
Formula
Example: Random Number Between 1 and 10
Complete Program
7. Generating Random Floating-Point Numbers
Formula
Example
8. Applications of Random Numbers
-
Dice rolling games
-
Lottery systems
-
Password generators
-
Simulations and modeling
9. Pseudo-Random Numbers
Definition
Numbers generated by rand() are called pseudo-random numbers because:
-
They are generated using a mathematical formula
-
They are not truly random
10. Common Mistakes While Using Random Numbers
-
Forgetting to call
srand() -
Using the same seed value
-
Calling
srand()multiple times -
Not limiting the range properly
11. Advantages of Random Numbers
-
Adds unpredictability
-
Useful in games and simulations
-
Helps in testing programs
-
Simple to implement
12. Limitations of rand()
-
Not suitable for cryptographic security
-
Limited randomness
-
Platform-dependent
RAND_MAX
13. Best Practices
-
Call
srand()only once -
Use
time(NULL)as seed -
Limit range carefully
-
Avoid using
rand()for security purposes
14. Sample Program: Dice Simulation
15. Summary of Random Number Functions
| Function | Purpose |
|---|---|
rand() |
Generate random number |
srand() |
Set seed value |
time() |
Get current time |
16. Conclusion
Random numbers in C are generated using the rand() function along with the srand() function to improve randomness. Though they are pseudo-random, they are very useful in games, simulations, and testing programs. Understanding random numbers helps programmers create dynamic and interesting applications.