-->

Wednesday, March 19, 2014

C function to implement Linear Search in 1-dimensional array

 C function to implement Linear Search in 1-dimensional array

  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");
}

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved