Here, you are treating the search function as though it returned a true or false (boolean) value.
if (searchArray(integerArray, SIZE, choice))
Indeed, the function is defined with a bool return type. But inside the function what value does it actually attempt to return?
1 2 3 4
|
if (found)
return index;
else
return -1;
|
Answer, it tries to return the array index (or subscript) where the element was found. Or if the element was not found, then it returns -1.
Thus the value indicating "success" is an integer in the range 0 to SIZE-1. And "fail" is the integer -1. When converted to a bool, that means most of the time, the value returned will be
true. The only case where it will return
false is when the item is successfully found as the very first element of the array.
To summarise: it's broken.
How to fix it? Change the function so it really does return an integer.
int searchArray (int a[], int size, int value)
(change both lines 10 and 47).
In addition, change the way the result is tested.
1 2 3 4
|
if (searchArray(integerArray, SIZE, choice) >= 0)
cout << choice << " is in the array." << endl;
else
cout << choice << "is not in the array." << endl;
|
Or do it like this:
1 2 3 4 5
|
int foundAt = searchArray(integerArray, SIZE, choice);
if (foundAt >= 0)
cout << choice << " is in the array at position "<< foundAt << endl;
else
cout << choice << "is not in the array." << endl;
|