×

Random function in C

Random function in C

In the C programming language, the rand() is a function used for Pseudo Random Number Generator (PRNG). The random number generated by the rand() function is not random. It is a sequence that repeats itself in a given time, but the period is so immense that it is usually ignored. In other words, the C library function int rand(void) returns a pseudo random number in the sane of 0 to RAND_MAX. The RAND_MAX is a constant whose default value may vary between the implementations, but it will be granted to be atleast 32767. The rand() function works by remembering a seed value generally used to compute the upcoming random number and the next new seed.

Randomization is a fundamental technique in an algorithm design. It allows a program to run quickly whenever the average case behavior of an algorithm is comparatively better than the worst case behavior. Randomization is generally used in games, both in entertainment and gambling. The latter application always gives the known example of a programmer getting into a problem due to writing bad code.

Header file:

 #include <stdlib.h>

Stdlib.h is a header that defines variable types, macros, and various functions for performing general compiler functions. Some of the variable types include size_t, wchar_t, div_t, ldiv_t; macros include NULL, EXIT_FAILURE, EXIT_SUCCESS, RAND_MAX, MB_CUR_MAX;

Syntax:

 int rand (void)
 Return values: 

The rand function always returns the next pseudo random number in series. The range of the number series that is returned ranges between 0 and RAND_MAX. The rand() generates values in the range of [0, RAND_MAX). On some machines and operating systems that use the GNU C library, RAND_MAX is equal to INT_MAX or 231-1 or might be as small as 32767. There are no strong guarantees about the quality of the random numbers that are generated by the rand() function, but the generated values should be good enough for casual use. They will have an advantage that as a part of the C language, it will be present in most places.

If the random numbers are generated using the rand() without calling the srand() function, the compiler will create the same sequence of numbers each time it runs.

E.g:

 #include <stdio.h>
 #include <conio.h>
 #include <stdlib.h>
 int main()
 {
 int i;
 printf (“ Print random numbers -> \n”);
 for ( i = 0; i < 10; i++)
 {
 printf (“%d”, rand()); //initializing random number funtion
 }
 printf (“\n”);
 return 0;
 }  

Output:

282930 939293 78382488 55325838348 838384

 #inlude <stdio.h>
 #include <conio.h>
 #include <stdlib.h>
 int main()
 {
 int i, n;
 time t;
 n = 5;
 srand ((unsigned) time(&t));
 for (i = 0; i < n; i++) //prints 5 random numbers from 0 to 49
 {
 printf (“%d \n”, rand() % 50);
 }
 return 0;
 } 

Output:

38 45 29 12 3 22

Many of the research on the pseudo random number generators over many years and better pseudo random number generators than rand are available. The Mersenne Twist runs about four times as fast as a rand in its C programming language, and it also passes a much wider battery of statistical tests.

There are many cryptographical secure pseudorandom number generators, out of which is the famous Blum Blum Shub. They cannot be predicted based on the output if seeded with a true random number value. Comparatively, cryptographic PRNG (Pseudo Random Number Generator) is slow for a day to day use.

srand():

You can set the seed for the rand function using srand() functions. This seed can only be set once, and before the first time, the rand() function will be called.

 Header file:
 stdlib.h 

Syntax:

int srand (unsigned int seed)

Arguments:

This only takes one argument:

Seed - an integer value used as a seed for a new series of pseudo random numbers.

Return values:

None

E.g.:

 #include <stdio.h>
 #include <stdlib.h>
 #include <time.h>
 #include <conio.h>
 int main()
 {
 srand (time(NULL));
 printf (“%d \n”, rand());
 srand (12);
 printf (“%d \n”, rand());
 return 0;
 } 

Output:

 1432462941
 1687063760 

Advantages of randomization

  • Calculations can be performed with a few integer arithmetic instructions.
  • Random numbers can be repeated,which and this is a great advantage when it comes to debugging that relies on random numbers.
  • The lower bits of the random numbers may not be as random as the higher bits. In general, a programmer can never use parts of a pseudo random number as another random number.
  • Some bit combination might not occur. If the constants are not chosen carefully, random numbers may not cover the range of possible numbers.

Related Topics

What is algorithm in C?

What is an algorithm? In computer programming languages, an algorithm is set of statement that solves a particular problem. In C, first step of every algorithm is Start and last step of...

3 minutes read.

10 Best IDEs for C or C++ Developers in 2024

Nobody can deny the fact that C and C++ were the first programming languages used by significant developers worldwide. Even now, newcomers who want to start programming are most frequently...

6 minutes read.

Attributes in C

Attributes are one of modern C++ key features. It is the process by which initiator can add more information to the language instead of introducing new keywords for every attribute....

4 minutes read.

SJF Scheduling Program in C

The SJF (shortest job first) or the shortest job next is the programming scheduling in the C. It is one of the CPU scheduling programming. The SJF is defined as...

4 minutes read.

How to Calculate Time Complexity in C?

What is time complexity? An algorithm's time complexity measures how long it takes to complete a task in relation to the size of the input. It should be noted that the...

5 minutes read.

fflush in C

In this article, we will understand what is fflush(), the need for fflush and fflush(stdin), and fflush(stdout). The fflush() function is used to clear the output buffer and move the buffered...

3 minutes read.

Fahrenheit to Celsius in C

Before going into conversion, we have to know what Fahrenheit and Celsius mean, these are both units to measure the temperature.In our daily life, we use both Fahrenheit and Celsius,...

1 minute read.

Command line arguments in C

Command line arguments in C The arguments that are generally passed from the line of command are referred to as command line arguments. These command line arguments are always handled by...

3 minutes read.

Typecast vs. typedef in C

Typecast vs. typedef in C Typecast In the C programming language, converting the data type from one form to another is known as type casting or the type conversion. It is a...

5 minutes read.

Doubly Linked list in C

To know the Doubly Linked List in C, first we should know about how the Linked List works. Linked List The Linked list is the linear data structure. In the Linked...

5 minutes read.

Pointers in C

Pointers in C: In the C programming language, a pointer is a pointer variable that points to the address of the other variable. It also stores the address of the...

4 minutes read.

#include in C

In the C programming language, #include is another way of inferring a standard, or a user defines file into the application or program. The preprocessor of the programming standard generally...

4 minutes read.

Do WHILE LOOP in C Programming Examples

Before understanding the programming examples of the Do-While loop, we have to know what is Do-While loop in C. So, let's start with the definition of the Do-While loop. What is...

5 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Bit Fields in C

The size of a structure in C is specified in bits. The primary goal of it is to use memory efficiently, once we understand that a bit's value must fall...

3 minutes read.

C/C++ Program to Find the Size of int, float, double and char

In this tutorial, we will learn how to use the sizeof operator to determine the size of each variable. Program to Determine Variable Size Write a C or C++ program to determine the...

2 minutes read.

Hexadecimal to Binary in C

What is hexadecimal? Hexadecimal defines a sequence of numbers centered on-16, i.e., before assigning the next number to a new location, it describes a numbering scheme that includes 16 sequential numbers as basic...

2 minutes read.

Sizeof in C

A pointer in C is defined as a variable that stores the information of the address of another variable. A pointer can be incremented or decremented, which means we can...

4 minutes read.

Comma Operator in C

What is a comma operator? The comma operator in the C programming language has the least priority. The comma operator is essentially a binary operator that operates on the first operand...

4 minutes read.

Format Specifier in C

Format Specifier in C Format specifiers can be described as an operator that is used to print the data referred by any object or variable in combination with the printf ()...

3 minutes read.