Well I initialize an array of 5000, along with using srand & rand numbers with a range. I want to Prompt the user to enter an integer to search (from the front of the array) & output the index location of the element found(-1 if not found). I attempted it, but no index output of the element. Any help is appreciated. Here is my code thus far:

#include <iostream> 
#include <cstdlib>
#include <time.h>  
using namespace std;

const int SIZE = 5000; //Initializing the Array
void fill(int []);
int search;
int index = -1;

int main (void) { 
          srand (time(0)); //Initializing Srand just once
          int int_ary[SIZE]; 
          fill (int_ary);
          int test = int_ary[rand()% ((0 + 16383)-8191)]; 
        /* Initalizing random numbers ranging from -8191 to 8192
        */     
        system("PAUSE");
 return 0; 
} 
/* fill initializes ary with random integers 
pre-condition: ary is correctly declared 
post-condition: ary is filled 
*/
void fill (int ary[]) { 
    const int from = -8192;
    const int to   = +8191;
for (int k=0; k<SIZE; k++) { 
        ary[k] = from + rand() % (to - from + 1); 

          cout << "Search any number between -8191 to 8192\n";
     cin >> search;
    for(int i = 0; i<SIZE; ++i)
    {
         if( ary[i] == search )
         {
               index = i;
         }
    }
    cout << index;
}

}

This:

int test = int_ary[rand()% ((0 + 16383)-8191)];

picks one value from your array or maybe from way off the end of your array (which has never been set), and makes the int test equal to that value. Why?

Anyway, inside your loop, you are doing this, over and over and over again:

set one element of the array to a random number
get input from user
look through array for a match

Shouldn't you set ALL the numbers in the array first, and then get the input from the user ONCE, and then look through the array for that value?

Edited 3 Years Ago by Moschops

Hey thanks for the reply. I actually finished with this program after much coding. I'm going to mark this as solved. I read your statement, and yes, there were fixes!!

This question has already been answered. Start a new discussion instead.