Write a C program for Linear Search.

procedure linear_search (list, value)

   for each item in the list
      if match item == value
         return the item's location
      end if
   end for

end procedure
Figure: Linear Search

#include <stdio.h>
 
int linear_search(int [], int, int);
 
int main()
{
    //!showArray(array)
int array[10], search, c, n, position;
 
   printf("Input number of elements in array\n");
   scanf("%d", &n);
 
   printf("Input %d numbers\n", n);
 
   for (c = 0; c < n; c++)
      scanf("%d", &array[c]);
 
   printf("Input a number to search\n");
   scanf("%d", &search);
 
   position = linear_search(array, n, search);
 
   if (position == -1)
      printf("%d isn't present in the array.\n", search);
   else
      printf("%d is present at location %d.\n", search, position+1);
 
   return 0;
}
 
int linear_search(int a[], int n, int find) {
int c;
 
   for (c = 0 ;c < n ; c++ ) {
      if (a[c] == find)
         return c;
   }
 
   return -1;
} 

Input number of elements in array
5
Input 5 numbers
5
4
3
2
1
Input a number to search
1
1 is present at location 5.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.