Thursday, July 2, 2015

Linear search

#include <stdio.h>

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

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

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

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

   printf("\nEnter 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;
}

No comments:

Post a Comment