generating six random lottery numbers using rand() and one dimensional array

Where am i going wrong here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Ch11AppE08
//generates and displays six unique random numbers for a lottery game.
//each lottery number can range from 1 to 54 only

#include <iostream>
using std:: cin;
using std:: cout;
using std:: endl;

int main ()
{
	int randomNum[6] = {rand () % (54 - 1 + 1)};
	
		for (int x = 0; x < 6; x += 1)
			cout << randomNum[x] << endl;

	return 0;
}
You are giving the random value only to the first element of the array.
You should make a loop to fill it properly.
(54 - 1 + 1) - 1 + 1 does nothing here
try this... hope it helps.

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
27
28
29
// include normal iostream etc...

#include <cstdlib>
using std::rand;
using std::srand;

#include <ctime>
using std::time;

int getRandNumb();

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

   int randomNum[6];
	
   for (int x = 0; x < 6; x++)
   {
      randomNum[x] = getRandNumb();
      cout << randomNum[x] << endl;
   }
   return 0;
}

int getRandNumb()
{
    return 1 + rand% 54;
} 
Last edited on
You forgot function parentheses on line 20 and you should had let the OP figure the solution out on his own
mybad... fixed, but as you can see from my example you will want to either implement srand, and seed it against time to get pseudo random numbers or write your own random function. (lots of examples on the net which can lead to confusion).

typically rand is called in that convention (rand()% number +1) or the above.

and make sure you declare an array before trying to stick data in it.

and as bazzy has already said, your for loop needs to stick data in the array, which you can see in my example the for loop has 2 purposes 1. filling the array and 2. outputting the contents.

EDIT: also the s in srand i believe stands for seed rand, you only ever need ot include this once in your program and needs to be a declaration like a variable, sticking it in a loop for example the for loop or getRand function would result in the same sets of numbers.

You can also use unsigned srand, but i belive rand only gives back numbers between 0-number you tell it
so including that is kinda redundant. because of the use of modulus... and +1 we get numbers between 1-whatever
Last edited on
Topic archived. No new replies allowed.