atakan yıldırım
atakan yıldırım

Reputation: 71

C++ Random Number Generator in Array

I'd like to write a program in C++, which will present 6 random numbers from 1 to 54. Below you could find the code. For some strange reason, when I run the program, I sometimes stumble upon an output like this:

Bugunku sansli loto sayiniz: 17 1 12 32 33 3418568

I couldn't figure out why the last number ignores my rule. Any help would be appreciated.

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

using namespace std;

int main()
{
    cout << "Bugunku sansli loto sayiniz: " << endl;
    srand(time(0)); 
    int myArray [5];
    for (int i = 0; i < 6; i++)
    {
        myArray [i] = (rand() % 55) + 1;
        cout << myArray [i] << '\t';
    }
}

Upvotes: 2

Views: 128

Answers (4)

Gaurav Jain
Gaurav Jain

Reputation: 346

If you want 6 items you need to make a array for six items

    int myArray[5];

this will provide 5 items where as

    int myArray[6]; 

this will provide you 6 items This will fix your problem

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172924

I couldn't figure out why the last number ignores my rule.

Because the last number accessed in the for loop is getting out of the bound of the array, dereference on it leads to UB. The for loop should be

for (int i = 0; i < 5; i++)
                    ~

Then i will be 0 ~ 4, loop 5 times, not 6 times as your code shown.

You might use range-based for loop (since C++11) to avoid such kind of mistake:

for (auto& i : myArray) {
    i = (rand() % 55) + 1;
    cout << i << '\t';
}

Upvotes: 3

tdao
tdao

Reputation: 17668

random numbers from 1 to 54

So this is incorrect as well: (rand() % 55) + 1;

You'll need (rand() % 54) + 1;

Upvotes: 1

STF
STF

Reputation: 1513

Because you went to myArray[5] at the last time and your array don't have this place so you got it

you need to write like that:

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

using namespace std;

int main()
{
    cout << "Bugunku sansli loto sayiniz: " << endl;
    srand(time(0)); 
    int myArray [5];
    for (int i = 0; i < 5; i++)
    {
        myArray [i] = (rand() % 55) + 1;
        cout << myArray [i] << '\t';
    }
}

Upvotes: 0

Related Questions