Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Random Function in C?
3.
rand() function
3.1.
Syntax
3.2.
Generate the 3 random numbers using the rand() function
3.3.
C
3.4.
Generate 10 random numbers from 1 to 100 using rand() function
3.5.
C
4.
srand() function
4.1.
Syntax
4.2.
Generate the random numbers using srand() function
4.3.
C
4.4.
C
5.
Generate 5 random numbers using srand() function
5.1.
C
6.
Generate 10 random numbers from 1 to 100 using srand() function
6.1.
C
6.2.
Generate the random numbers using srand() and time() function
6.3.
C
6.4.
Get a seeding value and print the random numbers using srand() function
6.5.
C
6.6.
Program to generate float random numbers
6.7.
C
6.8.
Program to generate values within a range
6.9.
C
7.
Difference Between rand () and srand () with example
8.
Frequently Asked Questions
8.1.
How to generate random number from 1 to 10 in C?
8.2.
How to generate a random number in C?
8.3.
What is random function of C?
8.4.
What is the use of random () function?
8.5.
In which library is rand () in C?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Random function in C

Author Vidhi Singh
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

You can't disagree with the fact that you have played Ludo at least once in your lifetime. If you have played it on your phone or any electronic device, you must have noticed that a random number from one to six appears every time someone rolls the dice. 

The random function is a way of generating a random number every time in C. In this article you will learn about the random function in C programming language.

random function in c

What is Random Function in C?

The random function generates random numbers within specified ranges. In C, it's facilitated by two built-in functions: rand() and srand().
As these functions are implemented inside the stdlib library in C, in order to use these functions, we need to include the ‘stdlib’ header file  as follows:

#include<stdlib.h>  

 

Let’s now see rand() and srand() functions for using random functions in more detail.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

rand() function

This function basically generates random numbers every time it is called inside a program. In general, the range of the generated number is 0 to RAND_MAX. Here RAND_MAX is any numeric value greater than or equal to 231-1 in most of the modern compilers. However, this may vary based on the compiler. But, the generated numbers will always be positive. It is apparent that the return type of this function is int.

Syntax

int rand(void)

Generate the 3 random numbers using the rand() function

Let’s try to print 3 random numbers

  • C

C

#include <stdio.h>
#include<stdlib.h>
int main()
{
for(int i=0;i<3;i++)
{
printf("The %d random number is: %d\n",i+1,rand());
}
return 0;
}

Output:

The 1 random number is: 1804289383
The 2 random number is: 846930886
The 3 random number is: 1681692777

Let’s try running this same program 2 more times and look at the output:

1st time:

The 1 random number is: 1804289383
The 2 random number is: 846930886
The 3 random number is: 1681692777

2nd time:

The 1 random number is: 1804289383
The 2 random number is: 846930886
The 3 random number is: 1681692777

Well, this is not something that we expected. Every time executed, it gives the same random numbers. So, the reason why this happened is that the compiler is not actually generating a random number every time, instead rand() function is deterministic. Deterministic means that it has specific rules by which it produces numbers. It pretends to be generating random numbers. It already has a sequence of numbers that it periodically displays repeatedly. Still, we never know what may happen as the length of that sequence is very large, so there never seems to be any repetition of numbers. 

In reality, what it is doing is a sort of transformation. 
Transformation can be like this:

Let a number be x. Here, ‘x’ is the seed. You will learn about seed later in this article.
Step 1: Multiply ‘x’ with 7 
Step 2: Add 59 to the product 

Suppose the number is 74 
After step 1: 74*7=518
After step 2: 518+59=577

To generate the next number
After step 1: 577*7=4039
After step 2: 4039+59=4098 

Of course, the way it has been actually implemented is not exactly like this, but I hope you got an idea.
Now, suppose you don't want the same sequence every time. You want it to be completely random for that we have another function srand().

Generate 10 random numbers from 1 to 100 using rand() function

Lets try to generate 10 random numbers between 1 and 100.

  • C

C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
int i;
printf("10 Random Numbers between 1 and 100:\n");
for (i = 0; i < 10; i++) {
// Generate a random number between 1 and 100
int random_number = rand() % 100 + 1;
printf("%d\n", random_number);
}

return 0;
}

Output:

10 Random Numbers between 1 and 100:
84
87
78
16
94
36
87
93
50
22

Explanation

In this program, srand(time(NULL)); seeds the random number generator using the current time so that each time you run the program, you get different random numbers. rand() % 100 + 1; generates a random number between 0 and 99, then adds 1 to shift the range to 1-100.

srand() function

Firstly, the main difference between the rand() function and srand() function is that the rand() function has a set sequence of numbers that it displays. They can be said as pseudo-random. In contrast, the numbers generated by the srand() function are random in the real sense.

The srand() function is able to do so by making use of random seed. A random seed is basically what determines the start of the sequence of random numbers. This also explains the same sequence produced by the rand() function; seed value is fixed, which is 1.

In the case of the srand() function, this value of seed can be changed, and therefore a different set of numbers are generated. The srand() function cannot be used without using the rand() function, and that too the srand() function can be used only once in the program. Of course, the rand() function can be used multiple times. 

Syntax

void srand(unsigned int seed)

Seed: This integer value will serve as the algorithm's seed for the pseudo-random number generator.

One essential part to remember is that the seed value should be an unsigned integer.

Generate the random numbers using srand() function

Let’s see the demonstration of the srand() function usage:

  • C

C

#include <stdio.h>
#include<stdlib.h>
int main()
{
printf("The first time\n");
srand(1);
for(int i=0;i<3;i++)
{
printf("The %d random number is: %d\n",i+1,rand());
}
return 0;
}

Output:

The first time

The 1 random number is: 1804289383
The 2 random number is: 846930886
The 3 random number is: 1681692777

Here, the seed value was set to 1. 

Let’s set it to 2 and see

The second time

The 1 random number is: 1505335290
The 2 random number is: 1738766719
The 3 random number is: 190686788

You see, the numbers have changed. But while using it in some programs, you should develop some mechanism such that you don’t have to change the seed value manually. It should happen automatically. Usually, the current time is used after converting it to an unsigned integer.

Something like this:

  • C

C

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
time_t t;
srand((unsigned)time(&t));
printf("The first using time\n");
for(int i=0;i<3;i++)
{
printf("The %d random number is: %d\n",i+1,rand());
}
return 0;
}

Let's run it.

Output:

The first using time
The 1 random number is: 326377040
The 2 random number is: 2004070931
The 3 random number is: 1225817359

Now, running it after some time and the output

The 1 random number is: 1806739476
The 2 random number is: 1641172133
The 3 random number is: 1121344098

 

There was no human interference in the above program, which is required when using it for real-life applications. This was one such way of doing it. You can explore more such ways.   

Generate 5 random numbers using srand() function

Following is the code in C to generate 5 random numbers using rand() function:-

  • C

C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0)); /* set seed for random number generation */
int num;
for (int i = 0; i < 5; i++) {
num = rand();
printf("%d\n", num);
}
return 0;
}

Output:

1280510876
589394469
2117297545
1284924662
2010053310

 

The code above generates 5 random numbers using the rand() function. The random number generator is seeded using the srand() function which is provided a changing value, in this case the value is current time.

Generate 10 random numbers from 1 to 100 using srand() function

Following is the code in C to generate 10 random numbers from 1 to 100 using rand() function:-

  • C

C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0)); /* set seed for random number generation */
int num;
for (int i = 0; i < 10; i++) {
num = (rand() % 100) + 1;
printf("%d\n", num);
}
return 0;
}

Output:

58
6
62
58
56
69
5
46
95
45

 

The code above generates 10 random numbers between 1 to 100 using the rand() function. Mod operation with 100 is performed on the output value of rand() function, this means it can lie between 0 to 99. 1 is added to make it lie between 1 to 100.

Generate the random numbers using srand() and time() function

Lets use the srand() function with the time() function to generate random numbers:

  • C

C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
// Seed the random number generator with the current time
srand(time(NULL));

int i;
printf("10 Random Numbers between 1 and 100:\n");
for (i = 0; i < 10; i++) {
// Generate a random number between 1 and 100
int random_number = rand() % 100 + 1;
printf("%d\n", random_number);
}

return 0;
}

Output:

10 Random Numbers between 1 and 100:
80
84
74
43
25
53
13
67
73
37

 

Explanation

In this program, we use srand(time(NULL)) to seed the random number generator with the current time, thus making the sequence of random numbers different each time the program runs. rand() % 100 + 1 generates a random number between 0 and 99, then adds 1 to shift the range to 1-100.

Get a seeding value and print the random numbers using srand() function

Lets generate 5 random numbers between 1 and 50 using a seed value entered by the user:

  • C

C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
unsigned int seed;

// Prompt the user to enter a seed value
printf("Enter a seed value: ");
scanf("%u", &seed);

// Seed the random number generator
srand(seed);

int i;
printf("5 Random Numbers between 1 and 50 using seed %u:\n", seed);
for (i = 0; i < 5; i++) {
// Generate a random number between 1 and 50
int random_number = rand() % 50 + 1;
printf("%d\n", random_number);
}

return 0;
}

Output:

Enter a seed value: 4
5 Random Numbers between 1 and 50 using seed 4:
2
34
25
27
14

 

Explanation

In this example, we ask the user to enter a seed value using printf() and scanf(). The user's input is stored in the variable seed. We seed the random number generator using srand(seed). The program then generates 5 random numbers between 1 and 50 using rand() % 50 + 1 and prints them to the console. The program terminates after printing the random numbers.

Program to generate float random numbers

We simply convert the originally generated values to float and divide by RAND_MAX to generate float values between 0 and 1. An example program is as follows:

  • C

C

#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("The float random value is:%f", ((float)rand()/RAND_MAX));
return 0;
}

Output:

The float random value is:0.840188 

You can increase the range very easily through multiplication or some other operations.

Program to generate values within a range

To generate values within a given number, we can use the following formula: rand()%range_value

Here, range_value is the integer less than which the values will be generated.
Can you figure out the maths behind this? It is fun doing this! 
 

An example program is:  

  • C

C

#include<stdio.h>
#include<stdlib.h>
int main()
{
int range=8;
printf("The random value less than %d is:%d\n",range,rand()%range);
printf("The random value less than %d is:%d",range,rand()%range);
return 0;
}

Output:

The random value less than 8 is:7
The random value less than 8 is:6

Difference Between rand () and srand () with example

Function rand() srand()
Purpose Generates a pseudo-random integer between 0 and RAND_MAX Seeds the random number generator to produce different sequences of numbers
Return Returns a pseudo-random integer Returns void
Usage Used to generate random numbers in a program Used to seed the random number generator
Behavior Does not require explicit seeding; may use a default seed Requires seeding to produce different sequences of numbers
Seeding Automatically seeded with a default value Requires manual seeding using a seed value (e.g., current time)
Example

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
   int i;
   printf("Random numbers using rand():\n");
   for (i = 0; i < 5; i++) {
       printf("%d\n", rand());
   }
   return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
   int i;
   unsigned int seed = time(NULL); // Get the current time as seed
   srand(seed);
   printf("Random numbers using srand():\n");
   for (i = 0; i < 5; i++) {
       printf("%d\n", rand());
   }
   return 0;
}

Frequently Asked Questions

How to generate random number from 1 to 10 in C?

We can generate random numbers in C between 1 and 10 using rand() and srand() functions. After passing the seed to srand(), we can calculate it by (rand() % 10) + 1.

How to generate a random number in C?

Random number in C is often generated using rand() and srand() functions. Both of them are often used together. To mimic randomness in a number we pass time as a seed in srand() function.

What is random function of C?

The rand() function in C generates pseudo-random integers between 0 and RAND_MAX.

What is the use of random () function?

rand() is used to generate random numbers for various applications like simulations, games, and cryptography.

In which library is rand () in C?

The rand() function is part of the standard C library, stdlib.h.

Conclusion

In this article, we have discussed random function in C programming, i.e., rand().  The rand() function in C provides a convenient way to generate pseudo-random numbers, crucial for diverse applications such as simulations, gaming, and cryptography. 

Also read reverse a number.

We hope that this blog has helped you enhance your knowledge regarding random functions in C, and if you would like to learn more, check out our articles on C language. Do upvote our blog to help other ninjas grow. 

Happy Coding!   

Live masterclass