Generate random numbers

This code generates random numbers within a given range by using the rand() function from the cstdlib library.

Code Example

#include <iostream>
using namespace std;

int main() {
    // initialize random seed
    srand (time(NULL));

    cout << "Random value between 0 - 9:\t";
    int randomInteger10 = rand() % 10 + 1;
    cout << randomInteger10 << endl;

    cout << "Random value between 0 - 99:\t";
    int randomInteger100 = rand() % 100;
    cout << randomInteger100 << endl;

    cout << "Random value between 1 - 100:\t";
    int randomInteger = rand() % 100 + 1;
    cout << randomInteger << endl;

    return 0;
}

Output first run

Random value between 0 - 9:	8
Random value between 0 - 99:	49
Random value between 1 - 100:	74

Output second run

Random value between 0 - 9:	1
Random value between 0 - 99:	66
Random value between 1 - 100:	92

Code Explanation

It starts by initializing the random seed using the srand() function and passing the current time in seconds obtained from time(NULL) as its argument. This is to ensure that each run of the program produces different random numbers.

The rand() function returns a random integer value and the % operator is used to restrict the range of the generated number. The formula rand() % n returns a random integer value between 0 and n-1. To generate a number between a and b, you can use the formula a + (rand() % (b - a + 1)).

In this code, three random integer values are generated, with ranges between 0 and 9, 0 and 99, and 1 and 100 respectively. The generated numbers are displayed using cout.