Whats wrong with this

I don't know why is not working?
a. Declare an integer constant SIZE to store the number of numbers
b. Declare an array of numbers with size SIZE
c. Fill the array of numbers with random numbers in the range 2-6
That is the code.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main ()
{
const int size {6};
int numbers [size];
srand (time(0));

for (int i{0}; i<size; i++) {
numbers[i] = rand()% 3+4 ;
}
cout<<"Random numbers "<<endl;
for (auto number : numbers){
cout<<number << " ";
}
cout<<endl;
}

}
"is not working" has never been a helpful element of a question.

If you remove the spurious final } then it compiles and runs.

It then generates 6 random numbers between 4 and 6 inclusive. Your question says 2 and 6 inclusive. So fix the line that sets that particular numbers[i].
Thanks
PLEASE learn to use code tags, they make reading and commenting on source code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/

HINT: you can edit your post and add code tags.

why is not working?

"not working" is too vague. Are you receiving compile errors? Run-time? Copy and paste your exact errors.

You have one too many closing brackets ( } ), delete the last one. Code tags and code formatting would have made the issue obvious.

rand()% 3 + 4; won't give you the required 2-6 range. rand()% 5 + 2; is the proper clamping.

Using <random> for C++ random numbers:
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
30
#include <iostream>
#include <random>

int main()
{
   // create a random number engine, seeded by std::random device
   // http://www.cplusplus.com/reference/random/default_random_engine/
   // http://www.cplusplus.com/reference/random/random_device/
   std::default_random_engine rnd(std::random_device{}());

   // create a uniform integer distribution from 2 to 6 inclusive
   // http://www.cplusplus.com/reference/random/uniform_int_distribution/
   std::uniform_int_distribution<int> dist(2, 6);

   const int size { 6 };
   int numbers[size];

   for (int i { }; i < size; i++)
   {
      numbers[i] = dist(rnd);
   }

   std::cout << "Random numbers:\n";

   for (const auto& number : numbers)
   {
      std::cout << number << ' ';
   }
   std::cout << '\n';
}
Last edited on
Topic archived. No new replies allowed.