×

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

Fseek Function in C

The fseek function is a function in the C standard library that changes the position of the file pointer in a stream-oriented file. It is typically used to move the...

3 minutes read.

Inline Function in C

Inline Function in C A normal function will become an inline function when the function prototype of that function is prepended with the keyword "inline". Inline functions are the function where...

4 minutes read.

How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps. Take each character from...

3 minutes read.

Null character in C

Introduction The Null character in the C programming language is used to terminate the character strings. In other words, the Null character is used to represent the end of the string...

3 minutes read.

Static function in C

The functions in the C programming language are by default global. This means the programmer can easily access the function which is outside from the file where it was initially...

3 minutes read.

Execution flow of C program

There are various steps of the execution of the C program that is given below. The following step of the execution Write source codes Preprocess Compile Link edit Load Execute Editor or...

1 minute read.

C program that does not Suspend when Ctrl+Z is Pressed

In Programming when a program breakdown and runs surprisingly in the terminal compiler the developer has the ability to prevent the program from running unequivocally. For expressly halting the program,...

3 minutes read.

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

20 minutes read.

Branching Statements in C

What is branching in c? Branching gets its name from the fact that the computer can select which branch to follow.Programs written in the C language execute statements one after the...

6 minutes read.

Floor() Function in C

Floor() function is a built-in function in C which is defined in the math.h header file. This function is used to return the nearest integer value which is less than...

4 minutes read.

Difference between while and do-while loop in C

Introduction Both 'While' and 'Do-While' loops in C mostly have a similar concept, and the code of both loops runs for mainly similar purposes. Both loops process the program/code in the...

3 minutes read.

Segmentation Fault in C

Segmentation Fault in C In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating...

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.

Call Back Function in Embedded C

Callback function are one the most remarkable systems in C. A callback function is any code that is passed as a contention to another code, so this is the last...

3 minutes read.

Binomial Coefficient Program in C

What is Binomial coefficient? In the given set of n possibilities, the binomial coefficient(n,k) indicates the order of choosing 'K' results from those possibilities. Binomial coeeficient of posistive n and k...

3 minutes read.

String in C

String is a collection of character or group of characters. In array, string of character is terminated by a null value “\0” and enclose between double quote. We can declare...

2 minutes read.

Difference between C and Java

C programming and Java programming are two of the earliest programming languages. C programming follows a procedural approach whereas Java programming follows an object-oriented approach. Java programming is a part...

3 minutes read.

Exit control loop in C

To examine the termination condition for an exit, we usually use an exit control loop in C. If the evaluation for termination condition results in true, then the control would...

3 minutes read.

Binary Search in C with Best and Worst Time Complexity

What is Binary Search? Binary search is an algorithm that is used to find an element in a sorted array efficiently. It has a time complexity of O(log n). It means...

3 minutes read.

Bank Account System in C using File Handling

This tells about the creation of bank account system using the C language and handling of files in C. Approach Let us see the approaches and the functions how they are covering...

5 minutes read.