Wednesday, 29 October 2014

linear search

//linear search
#include <stdio.h>
int main()
{
   int array[100], search, i, n;

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

   printf("Enter %d elements:\n", n);

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

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

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

   return 0;
}


OUTPUT

Enter the number of elements in array
5
Enter 5 elements:
1
2
3
4
5
Enter the number to search
5
5 is present at location 5.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.