C Program for Linear search

Searching in C

Searching, in normal ways,can be coined as”to find the hidden thing”. In data structure.the searching algorithm is used to find whether a given number is present and if it is present then at what location it occurs.

there are two types of searching algorithm present in data structure through which searching any data become more easy.

  • linear search or sequential search
  • Binary search

Linear Search in C

This is labelled as one of the simplest method for searching. In this ,the searching  is done sequentially in the list.This method can be performed on a sorted list  or an unsorted list.In case of sorted list searching starts from 0th element and continues until the element is found from the list or we get the greater value from the element we are searching.

The searching in unsorted list starts from 0th element and continues until the element or end of the list.

Implementation of Linear Search in C

Step 1-The list given is the list of elements in the an unsorted array.The array contains 6 Element.

Step 2-The element to be searched is ‘9’ as mentioned in the image,so ‘9’ is compared with all the element starting from 0th element.

Step 3- perform the searching procres until the element 9 is found or list ends.

 

linear 3

Algorithm of Linear search

1- i=1
2- if i>n,go to step 7
3- if A[i]=x,go to step 6
4- i=i+1
5- Go to step 2
6- print element x found at i
7- print element not found
8- exit

Program of linear search in C

#include <stdio.h> //header files 
void main () //main function
{ 
  int a[10] = {10, 23, 40, 1, 2, 0, 14, 13, 50, 9}; 
  int item, i,flag; 
  printf("\nEnter Item which is to be find\n"); 
  scanf("%d",&item); 
      for (i = 0; i< 10; i++) //looping logic 
{ 
// if else condition
  if(a[i] == item) 
{ 
    flag = i+1; 
    break; 
} 
 else 
   flag = 0; 
} 
   if(flag != 0) 
{ 
      printf("\nItem found at location %d\n",flag);  //printing the element which is to find 
} 
   else 
{ 
      printf("\nItem not found\n"); 
} 
}

Output

Enter Item  which is to be find

23

Item found at location  2

Summary
Review Date
Reviewed Item
Linear Search
Author Rating
51star1star1star1star1star

Please Login/Signup to comment