- C Programming Tutorial
- C - Home
- Basics of C
- C - Overview
- C - Features
- C - History
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
- C Programming Resources
- C - Questions & Answers
- C - Quick Guide
- C - Cheat Sheet
- C - Useful Resources
- C - Discussion
Random Number Generation in C
The stdlib.h library in C includes the rand() function that returns an integer randomly, between "0" and the constant RAND_MAX.
The rand() function generates pseudo-random numbers. They are not truly random. The function works on Linear Congruential Generator (LCG) algorithm.
int rand(void);
Example 1
The following code calls the rand() function thrice, each time it is likely to come with a different integer −
#include <stdio.h> #include<stdlib.h> int main() { printf("%ld\n", rand()); printf("%ld\n", rand()); printf("%ld\n", rand()); return 0; }
Output
Run the code and check its output −
41 18467 6334
The rand() function doesn't have a built-in mechanism to set the seed. By default, it might use a system specific value (often based on the time the program starts).
Note: The srand() function is used to improve the randomness by providing a seed to the rand() function.
Example 2
The following program returns a random number between 0 to 100. The random integer returned by the rand() function is used as a numerator and its mod value with 100 is calculated to arrive at a random number that is less than 100.
#include <stdio.h> #include<stdlib.h> int main(){ for(int i = 1; i <= 5; i++) { printf("random number %d: %d \n", i, rand() % 100); } return 0; }
Output
Run the code and check its output −
random number 1: 41 random number 2: 67 random number 3: 34 random number 4: 0 random number 5: 69
Example 3
You can also obtain a random number between a given range. You need to find the mod value of the result of rand() divided by the range span, add the result to the lower value of the range.
#include <stdio.h> #include<stdlib.h> int main() { int i, num; int lower=50, upper=100; for (i = 1; i <= 5; i++) { num = (rand() % (upper - lower + 1)) + lower; printf("random number %d: %d \n", i,num); } return 0; }
Output
Run the code and check its output −
random number 1: 91 random number 2: 55 random number 3: 60 random number 4: 81 random number 5: 94
The srand() Function
The stdlib.h library also includes the srand() function that is used to seed the rand() function’s random number generator.
You would use the following syntax to use the srand() function −
void srand (unsigned seed);
OR
int srand (unsigned int seed);
The seed parameter is an integer value to be used as seed by the pseudo-random number generator algorithm.
Note: If srand() is not initialized, then the seed value in rand() function is set as srand(1).
Usually, the srand() function is used with the value returned by time(NULL) (which represents the current time since the epoch) as a parameter to improve the randomness of the pseudo-random numbers generated by rand() in C.
Since the time value changes all the time, this will have different seed values, leading to more varied random sequences. As a result, if you generate random number multiple times, then it will likely result in different random value every time.
Example 1
Take a look at the following example −
#include <stdio.h> #include<stdlib.h> #include <time.h> int main() { srand(time(NULL)); printf("Random number: %d \n", rand()); return 0; }
Output
Every time a new random integer between 0 to RAND_MAX will be displayed.
Random number: 1436786055
Example 2
We can include srand() to generate a random number between a given range.
#include <stdio.h> #include<stdlib.h> #include <time.h> int main() { int i, num; time_t t; int lower = 100, upper = 200; srand((unsigned) time(&t)); for (i = 1; i <=5; i++) { num = (rand() % (upper - lower + 1)) + lower; printf("random number number %d: %d \n", i, num); } return 0; }
Output
Run the code and check its output −
random number number 1: 147 random number number 2: 171 random number number 3: 173 random number number 4: 112 random number number 5: 181
The random number generation offered by rand() function is not truly random. With the same seed, you'll always get the same sequence. It also has a limited range as it generates random numbers within a specific range (0 to RAND_MAX).
To improving the Randomness, you need to use a good seed value with high unpredictability like system time or a high-resolution timer. You can also use third party libraries for wider range random numbers.