Hello, very new to C++. I have to initialize an Array of 5000 and use the Srand & Rand, where the range would be -8191 to 8192. Let me provide what I have done so far
I'm not sure what is your intention. Is it to fill the array with random values in the range of -8191 to 8192 ?
Your current code seems to generate array subscripts which are in the range 0 to 8191 which is a bit awkward, as the array contains only 5000 elements.
Generate random in a particular range:
1 2 3 4
int rnd(int from, int to)
{
return from + rand() % (to - from + 1);
}
Thanks for the replies. Let me clarify a bit more what I have to do. "perform a search and display elements of an array. Initialize an integer array of 5,000 elements with random integers, using srand & rand functions in the range: -8192 to 8191 (duplicates permitted). Prompt the user to enter an integer to search (from the front of the array) & output the index location of the element found (negative 1 if not found)".
So starting out step by step by initializing an array, then using srand & rand for the range. Once I figured that out, i'll continue to do more coding.
So your fill function should do something like this:
1 2 3 4 5 6 7 8 9 10
void fill (int ary[])
{
constint from = -8192;
constint to = +8191;
for (int k=0; k<SIZE; k++)
{
ary[k] = from + rand() % (to - from + 1);
}
}
edit: The original post said: "where the range would be -8191 to 8192" while the newer post says: "-8192 to 8191"
I'll leave it for you to figure out which is required.
I didnt really understand what you want to do :D but as I understood,
-you will initialize an array of 5000 elements which are generated by rand() in the range -8192 to 8191
-and you will ask a number to search and show the index of that number
Appreciate the help people. Sorry about the range difference confusion. :P
EDIT: I think I understand the question of this program. It wants to produce an index of various numbers up to 5000. I.E [0] -945, [1] -47...[4999] 74.
Afterwards, i'll have to code in user input to search for a number.