Generate 6 random numbers for lottery

Hi

I am very new to c++ and I am trying my best to get a very basic grasp of things.

I have been doing an online course and set myself a task of generating 6 random numbers between 1 and 59 for the UK lottery. That shouldn't be too difficult I thought...

Here is my code:-

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

using namespace std;

//integers to be used in for and while loops and amount of balls
int i,num,line,numberofballs = 59;

bool lotterynumbers[59]; //array to store genertated numbers


int main(void)
{
srand(time(NULL)); // randomise seed
line = 0; //number of balls in a line set to zero and inc to 6

//set all elements in lottrynumbers array to false
for (i=0; i<numberofballs; i++)
{
lotterynumbers[i] = false;
}
//generate 6 random numbers and set that element to true
while(line<6)
{
num = (rand() % 59) + 1;
if (!lotterynumbers[num])
{
lotterynumbers[num] = true;
line++; //increment for stop condition of loop
}
}
//loop through array and when it's true print out that element
for (i=0; i<numberofballs; i++)
{
if(lotterynumbers[i])
{
cout << i << " ";
}
}

cout << endl; // new line

return 0; //finish succesfully
}


There we have it. It kind of works - most of the time - but very very occasionally it will only give me 5 numbers?
I realise my code may not be the 'prettiest' but can anyone shed any light as to why it sometimes only gives 5 numbers?

Your help is appreciated.

James
num = (rand() % 59) + 1; will give you array index 1-59
bool lotterynumbers[59]; — valid indices are 0-58
Please use code tags: [code]Your code[/code]
Read this: http://www.cplusplus.com/articles/z13hAqkS/


(rand() % 59) creates valid indexes from 0 to 58. +1 may create an index 59 which is out of bounds.

num = (rand() % 59) + 1; // Note: + 1 may create an invalid index

Ok sorry for not using tags!

from the sounds of it i am occasionally getting a mismatch because of my random numbers and array elements.

I will see if I can come up with a solution.

Thanks very much!!



If I change my code thus:-

num = (rand() % 59;

Then use this as before in order to change the elements to true.

Then change

cout << i << endl;

to cout << i + 1 << endl;

The plus 1 will shift all the numbers by 1 therefore representing the real world lottery balls because they start at ball 1 not 0?

Does that make sense!!
Yes, that would work.
Thanks for all your help, I don't think i would've ever spotted the schoolboy error!
At least i know what to check/look for now when doing something similar.

Thanks again.
Topic archived. No new replies allowed.