Before going to the program first let us understand what is a Linear Search?
Linear search:
Linear search is the simplest search algorithm. It is also called as sequential search.
Linear search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted.
For Linear search the list need not be ordered.
Related: C program for binary search
Program code for Linear Search in C:
#include<stdio.h> #include<conio.h> void main() { int a[10],i,size,item,pos,flag=0; clrscr(); printf("n Enter the size of an array: "); scanf("%d",&size); printf("n Enter the elements of the array: "); //LOOP TO STORE THE ELEMENTS for(i=0;i<size;i++) { scanf("%d",&a[i]); } printf("n Enter the element to be searched: "); scanf("%d",&item); //LOOP TO CHECK WHETHER THE SEARCH ELEMENT IS PRESENT OR NOT for(i=0;i<size;i++) { if(item==a[i]) { pos=i; flag=1; break; } } if(flag==1) printf("n The element is in the list and its position is: %d",pos+1); else printf("n The element is not found"); getch(); }
Step by Step working of the above C Program:
- For Linear Search, first the computer reads the array from the user.
- Then it read the element to be searched.
- Then it sets the value of flag = 0.
- Then using for loop the element to be searched is compared to all other elements of the array.
- If it find an equal match of the element then it assigns the value of ‘i’ to ‘pos‘ and also assigns flag = 1.
- Finally if flag = 1 , then it is printed as “the element is in the list and its position is (position)” else it is printed as “the element is not found”.
- Thus the program execution is completed.