Search This Blog

Loading...

Linear Search in C

Linear search in c: The following code implements linear (search algorithm) search is used to determine whether a given number is in a table in place and yet when it then place it occurs. It is also called sequential search. It is very simple and works as follows: Followed by each element with the element looking to compare until you find the desired item or the list ends.
/* Linear search c program */
#include <stdio.h>

int main()
{
   int array[100], search, c, n;

   printf("Enter the number of elements in array\n");
   scanf("%d",&n);

   printf("Enter %d integer(s)\n", n);

   for (c = 0; c < n; c++)
      scanf("%d", &array[c]);

   printf("Enter the number to search\n");
   scanf("%d", &search);

   for (c = 0; c < n; c++)
   {
      if (array[c] == search)     /* if required element found */
      {
         printf("%d is present at location %d.\n", search, c+1);
         break;
      }
   }
   if (c == n)
      printf("%d is not present in array.\n", search);

   return 0;
}
Output:
Enter the number of elements in array
6
Enter 6 numbers
5
6
9
2
4
7
Enter the number to search
2
2 is present at location 3.
Read More:
Linear search for multiple occurrences
Linear search using function in C
Linear search function using pointers in C 

No comments:

Post a Comment