Random number from a set of numbers

Hi, I am trying to develop a random number generator that will generate a series of numbers between 1000 and 9999. I can't figure out what I have to do. Can someone point me in the proper direction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main ()
{
    int f;
    char s;
    int l;
    cout << "Begin" << endl;
    for (int d = 0; d < 5; d++) {

    for (int i = 0; i < 4; i++)
    {
    l = rand();
    }

            f = (rand() % 26);
            s = (char) (f+ 65);

            cout << l << s << endl;


    }
}
First of all you need to use srand() to give a beginning seed value the rest of the rand() values can work off of.

This method is normally the preferred way to accomplish this. (Put it at the top of your main function)
srand(time(NULL))

After that is done you can use rand() which is set up like this
rand() % (Max - Min) + Min

So for your example
1
2
srand(time(NULL));
rand() % (9999 - 1000) + 1000


Will give you a random number between 1000 and 9999
Last edited on
Thanks! Can you tell me the significance in that null? It doesn't have to be in depth.
I haven't looked too much into it, but I can give you a quick explanation.

time() takes in a pointer to a time_t object, which then stores whatever value you passed into it. In this case passing NULL into the time function shows that you don't want to store a specific time_t object, and it should just use it's own default value (which in this case is the amount of seconds that have passed since January 1st 1970 I believe).

This is a good value to use for srand as it is always changing, you could just do srand(10) but the program would always output the same number whenever you ran it.

This pretty much sums it up for you as well
http://www.cplusplus.com/reference/clibrary/ctime/time/
Topic archived. No new replies allowed.