So I have a program here that's supposed to do the very simple job of searching through an Array of 100 integers to find a specific key. The linearSearch function in this program is supposed to be recursive, so I have to call the function from within itself. The program compiles fine, but for some reason only returns the first element 0, in the array no matter what search key you put in.
What am I not seeing? Thanks.
#include <iostream>
using namespace std;
int linearSearch(const int[], int, int);
int main()
{
const int arraySize = 100; //size of array
int a[arraySize]; //create array a
int searchKey; //value to locate in array a
for(int i = 0; i < arraySize; i++)
a[i] = 2 * i; //create data
cout << "Enter integer search key: ";
cin >> searchKey;
//attempt to locate search key in array a
int element = linearSearch(a, searchKey, arraySize);
//display results
if(element != -1)
cout << "Found value in element: " << element << endl;
else
cout << "Value not found" << endl;
system("pause");
}
//linearSearch Function ****Returns 0 as index all the time *************
int linearSearch(const int array[], int key, int sizeOfArray)
{
static int index = 0;
//if Out of range, return -1 (Value not found)
if(index >= sizeOfArray){return -1;}
//if array value = key, array index is returned
if(array[index] == key){return index;}
//if array value is not equal to key, add to index and call func again
if(array[index] != key)
{
index++;
linearSearch(array, key, sizeOfArray);
}
}
I'm taking the correct approach by declaring index as static, right?
~Thanks a lot, you guys were quick and a HUGE help. =)
staticindex is almost certainly a bad idea. It's effectively a global variable which never gets reset.return.