rand() Function in C++

 


The rand() function in C++ generates pseudo-random numbers and is defined in the <cstdlib> library.


1️⃣ Syntax

#include <cstdlib>  // Required for rand()
int randomNumber = rand();  // Generates a random number

✅ Returns a pseudo-random integer in the range 0 to RAND_MAX.
RAND_MAX is a constant (typically 32767 on most systems).


2️⃣ Generating Random Numbers in a Range

To get a random number in a specific range [min, max], use:

int randomNumber = min + (rand() % (max - min + 1));

📌 rand() % (max - min + 1) ensures the result is within [min, max].

🔹 Example: Generate Random Numbers from 1 to 100

#include <iostream>
#include <cstdlib>  // For rand() and srand()
#include <ctime>    // For time()
using namespace std;

int main() {
    srand(time(0));  // Seed for different random numbers each run

    cout << "Random number (1-100): " << (rand() % 100 + 1) << endl;

    return 0;
}

🔹 Output (Example)

Random number (1-100): 42

srand(time(0)) seeds the random number generator, so results vary each time.


3️⃣ Why Use srand(time(0))?

Without srand(time(0)), rand() generates the same sequence of numbers every time the program runs.
To introduce randomness, use:

srand(time(0));  // Uses current time as a seed

🔹 Example Without srand()

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    cout << rand() << endl;
    cout << rand() << endl;
    cout << rand() << endl;

    return 0;
}

🔹 Output (Always Same)

1804289383
846930886
1681692777

🚫 Numbers repeat every run because rand() is not seeded.


🔹 Example With srand(time(0))

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));

    cout << rand() << endl;
    cout << rand() << endl;
    cout << rand() << endl;

    return 0;
}

Different numbers every time! 🎲


4️⃣ Generate Multiple Random Numbers

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));

    cout << "Five random numbers (1-50): ";
    for (int i = 0; i < 5; i++) {
        cout << (rand() % 50 + 1) << " ";
    }

    return 0;
}

🔹 Output (Example)

Five random numbers (1-50): 23 9 45 38 12

5️⃣ Random Number Between -10 to 10

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(0));

    int randomNum = -10 + (rand() % 21);  // Range: [-10, 10]
    cout << "Random number (-10 to 10): " << randomNum << endl;

    return 0;
}

6️⃣ Summary

rand() generates pseudo-random numbers.
srand(time(0)) ensures different results in each run.
✔ Use rand() % range + min for custom range numbers.

Would you like a dice roll simulation using rand()? 🎲

Post a Comment

0 Comments