When I used this function, it return -1 even if element of array was there.
int linear_search(int arr[], int length, int target)
{
for (int i=0; i < n; i++) {
if (arr[i] == target){
return i;}
return -1;
}
}
I then removed curly braces and it worked
int linear_search(int arr[], int length, int target)
{
for (int i=0; i < n; i++)
if (arr[i] == target)
return i;
return -1;
}
The first function would return -1 on the first iteration if
arr[i] != targetbecause areturnstatement follows theifstatement inside the loop.Aside: I couldn't see the hidden braces at first. Consider adopting one of the following formatting styles: