- Traverse given array starting from first element.
 - Compare element at current index with given key.
 - If key matches with an element, return the index.
 - If key doesn’t match with any of elements, return -1.
 
//C program
for linear search using function
#include
<stdio.h>
     int main(void)
      {
       int array[] = { 10, 15, 9, 12, 50,32 };
       int key =
90,arraySize=0,i,result;
       //function declaration
       int
linearSearch(int array[],int n,int value);
      //finding the size(no of elements) of
array
       arraySize
= sizeof(array)/ sizeof(int);
       //function calling
      
result=linearSearch(array,arraySize,key);
       if(result!=-1)
         printf("Element %d found at
position %d.\n",key,result+1);
       else
        
printf("Element %d does not exist.\n",key);
              
return 0;
      }    
      //function definition
      int linearSearch(int array[],int n,int
value){
      int index=-1,i;
       for (i = 0; i < n; i++){                  
         if (array[i] == value){
            index=i;  //key found at index i
            break;
         }           
       }
              
return index;
      }
Please comment if you find anything incorrect, or you want to improve the topic discussed above. 

No comments:
Post a Comment