I was using an array linear search function to search in an array (the example array here is just a set of twenty int 0). But the "Value not found" statement still exists when there are values found in the main function.
#include<iostream>
#include<string>
using namespace std;
// linear search of key value in array[]
// return the index of first occurrence of key in array[]
// return -1 if key is not found in array[]
int linearSearch(const int array[], const int sizeOfArray, int key, int startPos) {
for (int j = startPos; j < sizeOfArray; ++j)
{
if (array[j] == key)
cout << j << ",";
startPos = j + 1;
}
return -1;
}
int main()
{
const int sizeOfArray = 20; // size of array
int a[sizeOfArray]; // declare array a
int searchKey; // value to locate in array a
// fill in some data to array
for (int i = 0; i < sizeOfArray; ++i)
a[i] = 0;
cout << "Enter an integer to search: ";
cin >> searchKey;
// try to locate searchKey in a
int element = linearSearch(a, sizeOfArray, searchKey, 0);
// display search results
if (element = -1)
cout << "Value not found" << endl;
else
cout << "Value found in element " << linearSearch(a, sizeOfArray, searchKey, 0) << endl;
return 0;
}
And the trial execution was like:
Just wondering what's wrong with it. How can I delete the "Value not found" here?