rand()
doesn't return a true-random, rather it returns a pseudo-random.
It all depends on the initial seed you provide to the random generator. If the initial seed is the same, then the consequent numbers you'll get from pseudo-random-algorithm is the same.
Then you should change the initial seed for the rand()
on each call (in this case, each execution of your program). What else is a better changing value than time
?
Note:
array[rand() % array[j]];
line on your code is highly vulnerable to segmentation fault by array index going out of bound.
Here is the solution.
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
// Initialize the srand seed.
srand (time(NULL));
int size = 5;
int array[size];
int Random;
for (int i = 0; i <5; i++)
{
cin>>array[i];
}
int index = rand() % size;
Random = array[index];
cout << Random << endl;
}
UPDATE:
As many others suggested, you can move to std::uniform_int_distribution
for better results. My answer only updates your initial code.