Need to write a program that finds values in an array. Having a bit of trouble figuring out how to count the number of comparisons it makes until it finds the value.
#include <iostream>
#include <stdlib.h>
usingnamespace std;
int linearSearch (int array[], int size, int searchValue)
{
for (int i = 0; i < size; i++)
{
if (searchValue == array[i])
{
return i;
}
}
return -1;
}
int main ()
{
int a[] = {17, 22, 8, 44, 86, 15};
int userValue;
cout << "Enter an integer:" << endl;
cin >> userValue;
int result = linearSearch(a, 6, userValue);
if(result >= 0)
{
cout << "The number " << a[result] << "was found at the element with index" << result << endl;
}
else
{
cout << "The number" << userValue << " was not found." << endl;
}
}
If you mean how many times you need to compare the search value with an array element, that is the return value + 1, or std::size(a) if the value is not found.