0

I want this program to generate 4 different series of 4 random numbers. The program is currently outputting the same numbers for each series. Any idea what's going on? I assume it's related to the seed but I don't know exactly what.

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

using namespace std;
int main()
{
    int lotArr[6];
    int j = 0;
    int k = 0;
    int m = 0;
    int n = 0;
    int i = 0;
    bool crit = false;

    //interates through 4 sequences
    for(int i = 0; i < 4; i++ )
    {
        srand(time(NULL));
        //generates each number in current sequence
        for(m = 0; m < 4; m++)
        {
            lotArr[m] = rand() % 30 + 1;
        }

        //output
        for(n = 0; n < 4; n++)
        {
            cout << lotArr[n] << " ";
        }
        cout << endl;
    }
    return 0;
}
dcjboi
  • 31
  • 6

1 Answers1

1

This is happening because time(NULL) returns UNIX timestamp in seconds. Now each one of your outer for loop executes in much less than a second. So, srand(time(NULL)) essentially sets the seed the same each loop. I'd suggest take the srand(time(NULL)); out of the loop and you'll be fine. Something like this:

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

using namespace std;
int main()
{
    int lotArr[6];
    int j = 0;
    int k = 0;
    int m = 0;
    int n = 0;
    int i = 0;
    bool crit = false;

    srand(time(NULL));

    //interates through 4 sequences
    for(int i = 0; i < 4; i++ )
    {
        //generates each number in current sequence
        for(m = 0; m < 4; m++)
        {
            lotArr[m] = rand() % 30 + 1;
        }

        //output
        for(n = 0; n < 4; n++)
        {
            cout << lotArr[n] << " ";
        }
        cout << endl;
    }
    return 0;
}
Faisal Rahman Avash
  • 1,268
  • 9
  • 13