Fill Array With Random Numbers in C++

Fill array with random numbers c++

IN this post, we will see how to fill array with random number in C++.

Arrays are the most commonly used data structures in the programming domain. We use arrays to store values of the same data type together at contiguous memory locations. In C++, we can create arrays of different data types in a very simple way. In this article, we will create an integer array and we will understand how we can populate our integer array with random numbers. An integer array is defined to store integral values. When we define an integer array, it is by default empty and does not contain any values initially. We will generate random numbers using the C++ library and then we will fill our array with these random numbers. 

The rand() Function in C++

The rand() function in C++ returns a pseudo-random number in the range [0, RAND_MAX) each time it is called. It uses an algorithm that returns a series of random and unrelated numbers each time the function is called. Since the numbers are generated using an algorithm that uses a seed value, we do not consider the numbers generated to be actually truly random, rather, we call such numbers pseudo-random numbers. 

We often use the srand() function in conjunction with the rand() function. This function is used to provide a seed value for the random generation of numbers. If we want to generate a different set of numbers each time we execute the rand() function, it is absolutely critical to provide a random seed each time. In case we do not provide a different random seed, we will get the same sequence of numbers each time we execute the rand() function. 

Although we can provide a random different seed value on our own to the srand() function, we often make use of the time() function. The time() function returns the current timestamp at the time of execution. Therefore, we can ensure that each time your program is executed, a different value will be passed to the srand() function as the parameter. It, in turn, ensures that a different set of values are produced by the random function, and we do not get the repeating and recurring values each time.  

The C++ library, stdlib.h, contains both of the rand() and srand() functions. On the other hand, RAND_MAX is a constant defined in the ctsdlib.h library. The time() function is defined in the time.h library. 

The rand() function outputs the number in the range [0, RAND_MAX]. It means a large number can be returned by the function. Therefore, to limit the range of the output, we often perform the modulo operation on the result. For example, if we want to limit our output to a number N, we will perform the modulo of output with N. However, in this process, we may get duplicate results, in essence, the numbers can be repeated. 

How to Fill the Array With Random Numbers in C++?

As we have already discussed, we can produce a series of random numbers with the help of the rand() function in C++. We will use the rand() function to generate a series of random numbers and fill them in the array with the following steps. 

  • First, we will create an integer array of a custom size. As the arrays are not initialized by default in C++, the array will contain garbage values initially. 
  • Then, we will use the srand() function with a seed value as time(NULL). As we have already discussed, the time() function returns the current timestamp which will be different each time we execute the program. It will ensure that every time we execute the program, a random and different set of values is produced instead of the recurring values. 
  • After seeding the srand() with the current timestamp, we will loop through the array using a loop control statement. 
  • In each loop cycle, we will generate a pseudo-random number using the rand() function. 
    • We can insert the pseudo-random number into our array using the array index and move forward to the next position in the array.  This is because the maximum number returned by the rand() function i.e.  RAND_MAX is equal to the maximum value of an integer in C++, in essence, INT_MAX. Therefore, no overflow or underflow shall occur.

We have implemented the above approach to fill the array with random numbers in C++ as follows.

Output:

You can notice the difference in output which shows that a different set of random values is produced each time the code is executed. 

How to Fill the Array With Random Numbers in a Range in C++?

If you don’t want such large numbers in the output array, you can perform the modulo operation on the result produced by the rand() function say M. Suppose that we have to use the random numbers between 0 and N. In such a case, we will perform the modulo operation M%N to create random number in the range 0 to N-1 in the array.

In the following program, we have implemented the approach to fill an array with random numbers within a range in C++.

Output:

Notice that the output values are now in the range [0,5), in essence, only 0, 1, 2, 3, or 4 are produced as output. Also, observe that certain values are repeated as we have already mentioned that it is a side effect of trimming that certain values may be repeated. 

Conclusion

We often work with random values and arrays and this article gives a detailed insight on how we can fill array with random numbers in C++. We have seen that we can produce the random values using the rand() function and use the srand() function to provide a seed. We have also seen how to fill an array with random numbers in a range in C++.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related Posts

  • How to initialize an array in Constructor in C++
    23 April

    How to initialize an Array in Constructor in C++

    Table of ContentsArraysConstructors of a ClassWays to initialize an array in Constructor in C++Initialize an array in Constructor With std::fill()Initialize an array in Constructor Using for LoopInitialize an array in Constructor Using Member Initializer ListConclusion This article discusses methods of initializing an array in constructor in C++. Let us first discuss arrays and constructors in […]

  • Write String to file in C++
    31 March

    Write String to File in C++

    Table of ContentsUsing the fstream Library to write String to File in C++Using the Insertion Operator (<<) With the fstream ObjectUsing the write() Function of the fstream LibraryUsing the fwrite() Function to write String to File in C++Conclusion The files are used to store the data permanently on a disk. This mitigates the problem of […]

  • Print Array in C++
    23 March

    Print Array in C++

    Table of ContentsIntroduction of ArraysDifferent Methods to Print an Array in C++print array in C++ by Traversing Indicesprint array in C++ Using for_each() Functionprint array in C++ Using Range-Based for Loopprint array in C++ Using Iteratorsprint array Using ostream_iterator() Function and copy() Functionprint array Using C++17 copy() Function and make_ostream_joiner() FunctionConclusion An array is a […]

  • Print Vector C++
    23 March

    Print Vector in C++

    Table of ContentsPrint Vector in C++ Using IndicesPrint Vector in C++ Using Range-Based for LoopPrint Vector in C++ Using for_each() FunctionPrint Vector in C++ Using IteratorPrint Vector in C++ by Overloading the Insertion Operator (<<)Print Vector in C++ Using copy() FunctionConclusion This article discusses the vector and how to print vector in C++. Vectors are […]

  • Print Map in C++
    15 March

    Print Map in C++

    Table of ContentsMap vs Unordered MapPrint Map in C++ Using IteratorPrint Map in C++ Using Range-Based for LoopPrint Map in C++ by Overloading the ostream Insertion Operator (<<)Print Map in C++17 Using Structure Binding and Range-Based for LoopPrint Map in C++17 Using for_each() FunctionConclusionReferences Maps in C++ store the data in form of key and […]

  • How to write binary files in C++
    14 March

    Write Binary Files in C++

    Table of ContentsOpening a File in Binary Mode Using fstream LibraryWriting the Binary File Using the write() Function of fstream LibraryWriting the Binary File Using the put() Function of fstream LibraryWriting the Binary File Using Insertion Operator (<<) Of fstream LibraryWriting the Structure Object to Binary File Using fstream LibraryConclusion In this post, we will […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.