Pages

This blog is under construction

Tuesday, January 8, 2019

C program for Linear Search

Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection.

C Program:

#include<stdio.h>

void main()
{
   int n, i, key, flag = 0,pos;
   printf("Enter the size of array\n");
   scanf("%d", &n);
   int a[n];
   printf("Enter %d elements\n", n);
   for(i=0; i < n; i++)
   scanf("%d", &a[i]);
   printf("Enter the element to search\n");
   scanf("%d", &key);
   for(i=0; i<n; i++)
      {
        if(a[i] == key)
        {
           flag = 1;
           pos=i+1;
           break;
         }
       }
  if(flag == 0)
     printf("Element not found");
  else
    printf("Element Found at %d position", pos);
}

Output:
Enter the size of array                                                                                                                              
5                                                                                                                                                    
Enter 5 elements                                                                                                                                     
11                                                                                                                                                   
33                                                                                                                                                   
55                                                                                                                                                   
88                                                                                                                                                   
77                                                                                                                                                   
Enter the element to search                                                                                                                          
88                                                                                                                                                   
Element Found at 4 position 

No comments:

Post a Comment