What are C rand() and srand() Functions?

What are C rand() and srand() Functions?

5 mins read4.3K Views Comment
Updated on Jul 10, 2024 16:16 IST

The purpose of this blog is to make you understand the rand() and sand() C programming functions. Let’s learn about them with the help of easy examples.

2023_03_C-rand-and-srand-Functions-1.jpg

In C programming, rand() and srand() are two commonly used functions to generate a random number. 

In this article, we will discuss the difference between these two functions in C, along with examples.  

Explore Online C Programming Courses

We will be covering the following sections: 

So, without further ado, let’s get started!  

C rand() Function 

The rand() function is a part of the standard C library and is used to generate pseudo-random numbers. Pseudo-random numbers are numbers that appear to be random but are actually generated by a deterministic algorithm. The rand() function generates a sequence of such numbers based on a seed value. 

The rand() function is included in the <stdlib.h> header file and has the following syntax: 


 
int rand(void);
Copy code

The rand() function takes no arguments and returns an integer value between 0 and RAND_MAX, which is a constant defined in the stdlib.h header file. The value of RAND_MAX is implementation-defined. This means, that in the case of the RAND_MAX constant, its value is not defined by the C language standard but is instead specified by the implementation or compiler. This means that different compilers or systems may have different values for RAND_MAX depending on how they choose to implement the rand() function. However, the standard guarantees that the value of RAND_MAX will be at least 32767. To generate a random number between a specific range, you can use the modulo operator (%). 

Here’s an example of generating a random number between 1 and 6 (inclusive) using the rand() function: 

 


 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
// Seed the random number generator with the current time
srand(time(NULL));
// Generate a random number between 1 and 6
int random_number = rand() % 6 + 1;
printf("The random number is: %d\n", random_number);
return 0;
}
Copy code

Output: 

The random number is: 4 

Note that before using the rand() function, it’s a good practice to seed the random number generator using the srand() function. The srand() function takes an unsigned integer value (the seed) and initializes the random number generator. It’s common to use the current time as the seed value, as shown in the example above. 

It’s important to note that the sequence of pseudo-random numbers generated by the rand() function is deterministic and repeatable if the same seed value is used. This can be useful in situations where you need to reproduce a sequence of random numbers. 

Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

4 K
2 months
– / –
6 months
– / –
1 month
3.5 K
3 months
15 K
2 months
– / –
2 months
– / –
50 hours
– / –
1 month
5.5 K
140 hours
– / –
4 months

C srand() Function 

The srand() function is used to seed the random number generator in the C standard library. The function takes an unsigned integer value as its argument, which is used to initialize the random number generator.  

Here’s the syntax for the srand() function: 


 
void srand(unsigned int seed);
Copy code

The seed argument is the seed value for the random number generator. This value is used to initialize the internal state of the generator. 

Here’s an example of using the srand() function to seed the random number generator with the current time. 

Example 1: 


 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
// Seed the random number generator with the current time
srand(time(NULL));
// Generate a random number between 0 and RAND_MAX
int random_number = rand();
printf("The random number is: %d\n", random_number);
return 0;
}
Copy code

Output: 

The random number is: 825366201 

In this example, we use the time() function from the <time.h> header that returns the current time as the number of seconds since the Unix epoch (i.e. January 1, 1970, at 00:00:00 UTC). The srand() function then uses this value to seed the random number generator. 

Seeding the random number generator with the current time is a good choice because the current time is constantly changing, and therefore, the seed value will be different every time the program runs. This ensures that the sequence of random numbers generated by rand() will be different each time the program runs. 

Programmers can then use The rand() function to generate a random number between 0 and RAND_MAX. 

It’s important to note that the srand() function should only be called once in your program to seed the random number generator. If you call it multiple times with the same seed value, you’ll get the same sequence of random numbers each time. If you call it with a different seed value, you’ll get a different sequence of random numbers. 

Also, it’s worth noting that the rand() function in the C standard library is not cryptographically secure and should not be used for security-critical applications or applications where unpredictable randomness is required. In such cases, programmers can use a cryptographically secure random number. For instance: 

  • randombytes() function in libsodium. 
  • RAND_bytes() function in OpenSSL. 
  • getrandom() function in Linux. 

 We are not going into further detail on the above functions as it is outside the scope of this article.  

Let’s look at more examples of using the srand() function in C. 

Example 2: Rolling Dice Generator 

In this scenario, we are creating a simple rolling dice game where the user can input the number of dice rolls they want to make. We will use srand() to seed the random number generator with the current time, ensuring that each run of the program will generate a different sequence of random numbers. 


 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
int num_rolls, i;
printf("Enter the number of dice rolls: ");
scanf("%d", &num_rolls);
// Seed the random number generator with the current time
srand(time(NULL));
// Generate the specified number of random dice rolls
for (i = 0; i < num_rolls; i++) {
int roll = (rand() % 6) + 1; // Generates a random number between 1 and 6
printf("Roll %d: %d\n", i+1, roll);
}
return 0;
}
Copy code

Output: 

Enter the number of dice rolls: 4 

Roll 1: 2 

Roll 2: 5 

Roll 3: 5 

Roll 4: 1 

Example 3: Random Password Generator 

In this example, we are writing a program that generates a random password consisting of a user-specified number of characters. We will use srand() to seed the random number generator with the user-specified seed value, ensuring that the program will generate the same sequence of random characters every time it is run with the same seed value. 


 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
int num_chars, i, seed_value;
printf("Enter the number of characters in the password: ");
scanf("%d", &num_chars);
printf("Enter a seed value for the random number generator: ");
scanf("%d", &seed_value);
// Seed the random number generator with user-specified value
srand(seed_value);
// Generate a random password of the specified length
printf("Random Password: ");
for (i = 0; i < num_chars; i++) {
char c = (char)((rand() % 94) + 33); // Generates a random printable ASCII character
printf("%c", c);
}
printf("\n");
return 0;
}
Copy code

Output: 

Enter the number of characters in the password: 5 

Enter a seed value for the random number generator: 4 

Random Password: 4P'{4 
What is Palindrome in C Programming?
Structure in C Programming: How to Create and Use Programs
If Else Statement in C Programming: Syntax and Examples

Difference between rand() and srand() 

Here’s a table highlighting the key differences between rand() and srand() functions: 

Function  Purpose  Syntax  Arguments  Return Value  Can be called multiple times? 
rand()  Generates a pseudo-random number  int rand(void)  None  An integer between 0 and RAND_MAX  Yes 
srand()  Seeds the random number generator  void srand(unsigned int seed)  seed: An unsigned integer value used to initialize the generator  None  No, it should only be called once 

As you can see, the main difference between rand() and srand() is their purpose and how their usgae. rand() generates a pseudo-random number whenever it is called, whereas srand() seeds the random number generator and sets its initial state. 

The rand() function takes no arguments, while srand() takes an unsigned integer value used as a seed for the random number generator. 

rand() can be called multiple times, while srand() should only be called once to initialize the generator. Multiple calls to srand() with the same seed value would produce the same random numbers.

Must explore- Top 80+ C Programming Interview Questions and Answers

Endnotes 

I hope that this article was useful in helping you learn how to use C rand() and srand() functions. Explore our C articles to find out more about the language and consolidate your knowledge of the fundamentals. 

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio