using namespace std;
/*Function Prototype*/
int linearSearch(int arr[], int size, int value); //for finding a particular value by linear search method
int main()
{
int array[50], //defining array of large size(50)
size,value,
index;
cout << "Enter the size of array: ";
cin >> size;
while(size<1||size>50) //testing if the size is not in the available range
{
cout << "Wrong Input(should be between 0to50)!"
<< "\nEnter again: ";
cin >> size;
}
cout << "Enter the array elements\n";
for( int i=0 ; i<size ; i++ ) //for getting input for individual elements
{
cout << "Enter the element "
<< (i+1)
<< ": ";
cin >> array[i]; //getting input for each element
}
cout << "Enter the value to search in the array: ";
cin >> value;
index=linearSearch(array,size,value); //calling function by passing array , size and value to be searched
if( index==-1 ) //if the desired value dioes not exist
cout << "The number "
<< value
<< " does not exist in the array.\n";
else //if the desired value existed
{
cout << "The number "
<< value
<< " exists in the array at index "
<< index
<< ".\n";
}
return 0;
}
/*Function Definition*/
int linearSearch(int arr[],int size,int value)
{
int index=-1; //intializing index with -1(because -1 can neither be the index)
for( int i=0 ; i<size ; i++ )
{
if(arr[i]==value) //checking if the value desired exists or not
{
index=i; //assigning index the index of the element at which the value exists
break; //break the loop id value is found
}
}
return index; //returning the index
}
No comments:
Post a Comment