Wednesday, 6 August 2014

Linear Search..


#include <stdio.h>
#include<conio.h>
int main()
{
    clrscr();
   int array[100], search, elements, limit;
   printf("Enter the number of elements in array\n");
   scanf("%d",&limit);
   printf("Enter the array elements.\n");
   {
                 for (elements=0; elements<limit;elements++)
                 scanf("%d", &array[elements]);
   }
   printf("Enter the number to search\n");
   scanf("%d", &search);
   for (elements=0;elements<limit; elements++)
   {
       if (array[elements]==search)    
          {
                    printf("%d is present at location %d.\n", search, elements+1);
                    break;
           }
     }
   if (elements==limit)
   printf("%d is not present in array.\n", search);
   getch();
   return 0;
}


Output:
Enter the size of the array: 5
Enter the elements of the array:
45
55
16
87
80

Enter the No to be search 55
55 is present at location 2

1 comment:

  1. Program can be improved by removing the limit constraint i.e. let the user enter n no. of entries, because its not necessary that we always know the last limit.
    and break the loop if we type like 'q', then let the end user search for desired element.

    ReplyDelete

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