Wolfgang-1 - 3 months ago 39

C++ Question

I am trying to create a linear search algorithm on c++ but I am having some trouble with my linearSearch function in my code. It is a simple for loop and I can't see what seems to be the problem, I ask the user to enter a key and if it is the a key within the array then it should give the correct position but it does not. Can anyone see where I am went wrong in my implementation?

`#include <iostream>`

#include <ctime>

#include <cstdlib>

using namespace std;

int linearSearch(int arr[],int size, int key){

for(int i = 0; i < size; ++i){

if(key == arr[i]){

return i;

}else{

return -1;

}

}

}

int main() {

const int size = 20;

int numbers[size];

srand((unsigned) time(0));

for(int i = 0; i < size; ++i){

numbers[i] = (rand() % 100) + 1;

cout << numbers[i] << " ";

}

cout << endl;

int key;

cout << "Enter a key to search for: " << endl;

cin >> key;

int retValue = linearSearch(numbers,size,key);

if(retValue >= 0){

cout << "Key found at position " << retValue << endl;

}else{

cout << "Key not found" << endl;

}

return 0;

}

Answer

The problem is here:

```
if(key == arr[i]){
return i;
}else{
return -1;
}
```

You return either i or -1 after the first comparison, so the rest of the array is never searched at all. You should remove the `else return -1`

clause and `return -1`

only at the end of the function, instead.

If you do this the `linearSearch`

function should look like:

```
int linearSearch(int arr[],int size, int key){
for(int i = 0; i < size; ++i){
if(key == arr[i]){
return i;
}
}
return -1;
}
```