- C Programming Tutorial
- C - Home
- Basics of C
- C - Introduction
- C - Features
- C - Basics
- C - History
- C - Structure of C Program
- 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 - String Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
C Programming - C Random Number Generation
![]() Share with a Friend |
C Programming - C Random Number Generation
Random Number Generation in C
In C, random numbers are generated using the standard library functions provided in the <stdlib.h> header file. These functions can be used to generate pseudo-random numbers. Pseudo-random numbers are generated using algorithms that produce sequences of numbers that approximate the behavior of random numbers. However, they are not truly random because they are based on an initial value known as the seed.
Key Functions for Random Number Generation:
- rand(): The rand() function generates a pseudo-random integer.
Syntax:
C
int rand(void);
- Returns: A random integer in the range 0 to RAND_MAX. RAND_MAX is a constant defined in <stdlib.h> and represents the maximum value returned by rand(). The value of RAND_MAX can vary, but it is at least 32767 on most platforms.
- srand(): The srand() function sets the seed for the random number generator used by rand(). If you do not set the seed, the random number generator will use the same seed every time, producing the same sequence of numbers.
Syntax:
C
void srand(unsigned int seed);
- Parameter: seed is the initial value for the random number generator.
- Usage: You should call srand() once at the beginning of your program to set the seed, typically using the current time to ensure a different sequence each time you run the program.
- RAND_MAX: This is a constant defined in <stdlib.h>. It represents the maximum value that rand() can return. It is typically 32767 or higher.
Example:
C
printf("RAND_MAX: %d\n", RAND_MAX);
Example of Generating Random Numbers:
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Set the seed using the current time
srand(time(NULL));
// Generate and print 5 random numbers
for (int i = 0; i < 5; i++) {
int random_number = rand(); // Generate random number
printf("Random Number %d: %d\n", i+1, random_number);
}
return 0;
}
Explanation:
- Seeding the Random Number Generator:
- srand(time(NULL)): The time(NULL) function from the <time.h> library returns the current time in seconds since the Unix epoch. Using this value as the seed ensures that the sequence of random numbers is different each time you run the program.
- srand() must be called only once at the beginning of the program, before generating random numbers.
- Generating Random Numbers:
- rand(): This function generates a pseudo-random integer. Each call to rand() returns a new number in the range 0 to RAND_MAX.
Generating Random Numbers within a Specific Range:
To generate a random number in a specific range, you can use the modulus operator (%) to limit the value of the random number.
Example: Generating a Random Number Between a and b:
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Set the seed using the current time
srand(time(NULL));
int a = 10, b = 50;
int random_number = (rand() % (b - a + 1)) + a; // Random number in [a, b]
printf("Random Number between %d and %d: %d\n", a, b, random_number);
return 0;
}
Explanation:
- (rand() % (b - a + 1)) ensures that the random number is in the range 0 to (b - a).
- Adding a shifts the range to be between a and b.
Generating Floating-Point Random Numbers:
If you need random floating-point numbers between 0 and 1, you can convert the result of rand() to a floating-point number.
Example:
C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Set the seed using the current time
srand(time(NULL));
// Generate random floating-point number between 0 and 1
float random_float = (float) rand() / RAND_MAX;
printf("Random Float: %f\n", random_float);
return 0;
}
Explanation:
- (float) rand() converts the integer result of rand() into a floating-point number.
- Dividing by RAND_MAX ensures that the result is a number in the range [0, 1).
Common Issues:
- Same Sequence of Random Numbers:
- If you don't call srand() or use the same seed, rand() will generate the same sequence of numbers every time you run the program. To get different sequences, always use srand() with a different seed, such as the current time.
- Limited Range:
- The range of rand() is limited by RAND_MAX. To get a wider range, you can combine multiple calls to rand(), or use a better random number generation library, such as random() in POSIX or <random> in C++.
Summary:
- rand() generates pseudo-random numbers.
- srand() sets the seed for random number generation, ensuring different sequences of numbers in each run.
- Use the modulus operator (%) to limit the range of random numbers.
- For floating-point random numbers, divide the result of rand() by RAND_MAX.
This covers the basics of random number generation in C. You can experiment with these functions to fit your needs, whether it's generating random integers, floating-point numbers, or limiting the range.
