Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
4.
Return Value
5.
Example of rand()
6.
Time and Space Complexity
6.1.
Time Complexity
6.2.
Space Complexity
7.
Frequently Asked Questions
7.1.
Is it possible to generate random floating-point numbers using rand()?
7.2.
Can rand() generate negative random numbers?
7.3.
Is rand() suitable for cryptographic purposes?
8.
Conclusion
Last Updated: Nov 29, 2024
Easy

C++ Random Number

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Random numbers are an essential part of many computer programs, from games to simulations. These are useful where you need to create chances or create random situations like you are building a game that relies on chances or a program that generates unique test cases. To generate these random numbers, C++ provides built-in functions that make it easy to generate these numbers. 

C++ Random Number

In this article, we'll discuss the basics of using the rand() function to generate random numbers, like its syntax, parameters, return value, and examples. We'll also discuss the time and space complexity of rand() and look at some applications.

Syntax

The syntax for using the rand() function in C++ is very simple. Let’s see how you can generate a random number using rand():

#include <cstdlib>
#include <iostream>

int main() {
    int randomNumber = rand();
    std::cout << "Random number: " << randomNumber << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Random number: 1804289383
 

 

To use rand(), you need to include the `<cstdlib>` header file in your C++ program. This header file contains the declaration of the rand() function along with other useful functions for performing general-purpose math operations.

The rand() function takes no parameters & returns a pseudo-random integer between 0 & RAND_MAX, where RAND_MAX is a constant defined in the `<cstdlib>` header. The exact value of RAND_MAX may vary depending on your system, but it is guaranteed to be at least 32767.

It's important to note that the rand() function generates pseudo-random numbers, which means that the sequence of numbers it produces is deterministic & will be the same each time you run the program, unless you seed the random number generator with a different value (more on that later).

Parameters

The rand() function does not take any parameters. It is a standalone function that generates a random number whenever it is called, without the need for any input arguments.

However, it's worth mentioning that the behavior of rand() can be influenced by seeding the random number generator using the srand() function. The srand() function allows you to specify a seed value that determines the starting point of the pseudo-random number sequence.

For example: 

#include <cstdlib>
#include <ctime>
#include <iostream>

int main() {
    srand(time(0));  // Seed the random number generator with the current time
    int randomNumber = rand();
    std::cout << "Random number: " << randomNumber << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Random number: 123456789


In this example, we use the srand() function and pass it the current time obtained by calling time(0). This ensures that each time the program is run, the random number generator is seeded with a different value, resulting in a different sequence of random numbers.

Seeding the random number generator is crucial when you want to generate different random numbers each time your program runs. Without seeding, the rand() function will produce the same sequence of numbers every time, which may not be desirable in many situations.

Return Value

The rand() function returns a pseudo-random integer between 0 and RAND_MAX, inclusive. RAND_MAX is a constant defined in the `<cstdlib>` header and its value is guaranteed to be at least 32767.

It's important to note that the range of numbers generated by rand() is fixed and depends on the value of RAND_MAX. If you need random numbers within a specific range, you'll need to perform some additional calculations.

For example: 

#include <cstdlib>
#include <iostream>

int main() {
    int min = 1;
    int max = 10;
    int randomNumber = min + (rand() % (max - min + 1));
    std::cout << "Random number between " << min << " and " << max << ": " << randomNumber << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Random number between 1 and 10: 7


In this example, we define the range of numbers we want to generate (from `min` to `max`, inclusive). To generate a random number within this range, we use the formula `min + (rand() % (max - min + 1))`. This formula takes the remainder of `rand()` divided by `(max - min + 1)` and adds it to `min`, ensuring that the resulting number falls within the desired range.

Example of rand()

#include <iostream>
#include <cstdlib>
#include <ctime>


int main() {
    // Seed the random number generator with the current time
    srand(time(0));


    // Generate a random number between 1 and 100
    int min = 1;
    int max = 100;
    int randomNumber = min + (rand() % (max - min + 1));


    // Display the random number
    std::cout << "Random number between " << min << " and " << max << ": " << randomNumber << std::endl;

    // Generate 5 random numbers between 1 and 10
    std::cout << "5 random numbers between 1 and 10:" << std::endl;
    for (int i = 0; i < 5; i++) {
        int randomNum = 1 + (rand() % 10);
        std::cout << randomNum << " ";
    }
    std::cout << std::endl;


    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Random number between 1 and 100: 42
5 random numbers between 1 and 10:
7 3 10 1 5



In this example, we start by seeding the random number generator using `srand(time(0))` to ensure different random numbers are generated each time the program runs.

Next, we generate a random number between 1 and 100 using the formula `min + (rand() % (max - min + 1))`. We store the result in the `randomNumber` variable and display it using `std::cout`.

We then demonstrate generating multiple random numbers within a specific range. In this case, we generate 5 random numbers between 1 and 10 using a for loop. Each iteration of the loop generates a new random number using the formula `1 + (rand() % 10)` and displays it.

The output of this program will be different each time you run it, as the random number generator is seeded with the current time. 

Output: 

Random number between 1 and 100: 42
5 random numbers between 1 and 10:
7 2 9 1 5


This example showcases the basic usage of rand() and how you can generate random numbers within a specific range. You can adapt this code to suit your specific needs and incorporate random numbers into your C++ programs.

Time and Space Complexity

Time Complexity

  • Generating a random number using rand() takes constant time, O(1). The rand() function performs a simple mathematical operation to generate a pseudo-random number, and the time taken does not depend on the size of the input or any other factors.
     
  • Seeding the random number generator with srand() also takes constant time, O(1). The seeding process initializes the internal state of the random number generator, which is a one-time operation.

Space Complexity

  • The space complexity of using rand() is also constant, O(1). The rand() function does not require any additional memory allocation or storage that grows with the size of the input. It uses a fixed amount of memory to store the internal state of the random number generator.

It's worth noting that the time and space complexity of rand() are independent of the range of numbers being generated. Whether you generate numbers between 0 and RAND_MAX or within a specific range using additional calculations, the complexity remains constant.

However, it's important to keep in mind that the rand() function is not suitable for cryptographic purposes or applications that require high-quality random numbers. The pseudo-random numbers generated by rand() have certain limitations and patterns that may be predictable. For cryptographic needs, it's recommended to use cryptographically secure random number generators provided by libraries such as <random>.

Frequently Asked Questions

Is it possible to generate random floating-point numbers using rand()?

Yes, you can generate random floating-point numbers by dividing the result of rand() by RAND_MAX and casting it to a floating-point type.

Can rand() generate negative random numbers?

No, rand() generates non-negative integers between 0 and RAND_MAX. To generate negative numbers, you can subtract a random number from a desired negative value.

Is rand() suitable for cryptographic purposes?

No, rand() is not cryptographically secure and should not be used for cryptographic purposes. Use dedicated cryptographic random number generators for such needs.

Conclusion

In this article, we discussed the rand() function in C++ for generating random numbers. We looked at its syntax, parameters, and return value with examples. We also discussed the time and space complexity of rand() and its limitations for cryptographic purposes. 

You can also check out our other blogs on Code360.

Live masterclass