
- C - Home
- C - Overview
- C - Features
- C - History
- C - Standards
- C - Environment Setup
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Basic Syntax
- C - User Input
- C - printf Function
- C - Format Specifiers
- Lexical Elements in C
- C - Tokens
- C - Keywords
- C - Identifiers
- Variables and Constants
- C - Variables
- C - Constants
- C - Const Qualifier
- C - Linkage
- Data Types and Type Conversions
- C - Data Types
- C - Literals
- C - Escape sequences
- C - Booleans
- C - Integer Promotions
- C - Character Arithmetic
- C - Type Conversion
- C - Type Casting
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Unary Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Miscellaneous Operators
- Decision Making & Control Statements
- C - Decision Making
- C - if statement
- C - if...else statement
- C - if...else if Ladder
- C - Nested if statements
- C - Switch statement
- C - Nested switch statements
- C - Switch Case Using Range
- Loops in C
- C - Loops
- C - For Loop
- C - While Loop
- C - Do...while Loop
- C - For Loop vs While Loop
- C - Nested Loop
- C - Infinite Loop
- C - Break Statement
- C - Continue Statement
- C - Goto Statement
- Functions in C
- C - Functions
- C - Function Prototype
- 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
- C - Predefined Identifier __func__
- 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
- C - Dynamic Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Character Arrays
- C - Special Characters
- Structures and Unions in C
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Dot (.) Operator
- C - Lookup Tables
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- 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 - Function Pointers
- C - Array of Function Pointers
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Pointer to an Array
- C - Pointers vs. Multi-dimensional Arrays
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Const Pointers & Pointer to Const
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Restrict Keyword
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Initialization of Pointer Arrays
- Storage Classes and Qualifiers
- C - Storage Classes
- Memory Management in C
- C - Memory Management
- C - Memory Address
- Preprocessors in C
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- File Handling in C
- C - File I/O (File Handling)
- C - Input & Output
- Constants and Literals in C
- C - Macros
- C - Header Files
- 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
- C Online Compiler
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() functions 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.