Search

Wednesday, March 19, 2014
0 comments

C function to implement Linear Search in 1-dimensional array

9:47 AMWednesday, March 19, 2014

  C function to implement Linear Search in 1-dimensional array:

int linear_search(int arr[ ], int n, int key)
{
  int success=0,i=0; /* initial index is 0 */
  while ((i<n)&& (success == 0))
    {
       if (arr[i] == key)
       success = 1;
       i= i+1;
     }
  return success;
}

This C function returns 1 (TRUE) if the search is successful, otherwise it returns 0 (FALSE). The same function can be written using for statement compactly as follows:
int linear_search(int arr[ ], int n, int key)
{
  int success=0,i; /*initial index is 0*/
  for(i=o; i<n&& success == 0;i++)
    if(arr[i]==key)
      success = 1;
 return success;
}

If we want to display the "successful" or "unsuccessful" message in the function itself instead of returning 1 or 0, then we can just change the function code as follows:
void linear_search(int arr[ ], int n, int key)
{
  int success=0,i; /*initial index is 0 */
  for(i=0;i<n&&success == 0;i++)
   if(arr[i] == key)
    success = 1;
 if(success==1)
  printf("Search successful");
else
  printf("Search unsuccessful");
}

Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top