linear search in an array

                                               linear search




search operation in an array or searching an element in an array is the process of finding an element or the location if an element within an array

algorithm

step 1. start

step 2. set i=0

step 3.repeat step 4 and 5 for i=0 to i<n

step 4. if arr[i]=x then jump to step 7

step 5.set i= i+1

step 6. end the step 3 loop

step 7. print x found at i+1 position and go to step 9

step 8. print x not found if arr[i]!=x (after al the iteration of the above for loop )

step 9. stop

variables

1.arr = name of the array

2. n = size of the array 

3.i = loop counter 

4. x = the data element to be search 


 implementaton

#include<stdio.h>

int main()

{

     int i, n, x;

     int a[10];


     printf("Enter the size of the array: ");

     scanf("%d", &n);


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


     for(i = 0; i < n; i++)

        scanf("%d\n", &a[i]);


     printf("\nEnter the element to search: ");

     scanf("%d", &x);


     for(i = 0; i < n; i++)

     {

         if(a[i] == x)

         {

             printf("%d found at %d position.", x, i+1);

             return 0;

         }

     }


     printf("%d not found", x);

     return 0;


}

output:    
Enter the size of the array: 6

Enter 6 elements:
8
9
7
5
9
6
7

Enter the element to search: 7 found at 3 position.
Process returned 0 (0x0)   execution time : 18.492 s
Press any key to continue.




 

Post a Comment

0 Comments