Generate a random element in C++ from an array

In this discussion, we will see how to output a random element from an array in C++.

We will make use of the rand() function which is an inbuilt function of C++ to generate random numbers.

This function always produces a random number between 0 and RAND_MAX.

Here RAND_MAX is the maximum value and a constant in the C++ library.

Next, we will see why we are using srand() in our program.

srand() is used to set the starting point for producing random numbers.

Even if this is not called in the program we may not end up with errors or wrong results, by default it sets the value of seed to 1.

If we want to modify this value, we need to make use of the srand() function to set up a new seed value.


Code to generate a random element in C++ from an array:

In this code, we are using a variable to get a random position of the array.

We need to take care of the errors like “index out of bound” so we need to do modulus with the array size so that the

rand() function will always generate a number in between 0  and (array size -1).

#include <iostream>
#include <time.h>
using namespace std;

int main ()
  int array[10] = {1,2,3,4,5,6,7,8,9,10};
  int randompos = rand() % 10;
  cout << array[randompos]<<endl;;



In this way, we can generate a random element from an array in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *