Pick a random element from an array in C++

In this C++ tutorial, we will learn how we can write a program to pick a random element every time from an array in C++.

Let’s briefly discuss the C++ functions that will help us in generating random numbers later in this tutorial.

• rand()
• srand()

rand() function in C++

The rand() function is an inbuilt function of C/C++ library. It helps to produce random numbers in a range in range between 0 and RAND_MAX. The seed used for this function’s algorithm is initialized by a distinctive value of srand().

The range of the random numbers is determined using the module of the returned value by the range span and by adding the initial value of the range.

Example:

```a = rand() % 100; //ranges from 0 to 99
b = rand() % 100 + 2; //ranges from 2 to 101```

srand() function in C++

The srand() function is used to set the starting point with seed for producing the pseudo-random numbers.

Syntax:

`srand(unsigned seed)`

The seed by default sets as srand(1) if the seed() function doesn’t call in the program.

Program to pick a random element from an array in C++

Step1: First import the necessary headers file to the program.

```#include <iostream>
#include <time.h>```

Basically, we get the same random number each time while running a program, as it uses an algorithm that is pre-determined by the system.

So, in order to get the truly random number, we will take time as the random seed and then reduce down the range as per our requirement. That’s why we are including the time.h header file to do so.

Step2: Now, we will initialize the random seed using the time() function.

`srand ( time(NULL) );`

Step3: Create an array by adding some elements to it.

`char arrayNum[5] = {'8', '6', '7', '0','3'};`

Step4: initialize a variable that will store the pseudo-random number between a given range.

`int RanIndex = rand() % 5; //Generates random number between 0 and 4`

Step5: Finally, print the array element by passing the Ranindex as the index number to the array.

`cout << arrayNum[RandIndex];`

Here is the complete C++ program:

```#include <iostream>
#include <time.h>
using namespace std;
int main ()
{
srand ( time(NULL) );

char arrayNum[5] = {'8', '6', '7', '0','3'};
int RanIndex = rand() % 5;
cout << arrayNum[RanIndex];
}```

Output-1:

`7`

Output-2:

`3`

We will get a random element every time when we run the program as shown above.

Hope you have enjoyed reading this tutorial and learned how to pick a random element from an array in C++.

You can also read, How to Generate random numbers in a specific range in Java