Linear Search with example - Tutorials Hub

# Tutorials Hub

Free Online Tutorials. Tutorials Hub Provides Programming Tutorials like c, cpp, java, dbms, sql, Android, flutter, dart, mobile app development, daa, OS, CA , etc

## Linear Search

### What is the linear Search?

The sequential/linear search method is mainly applicable for searching an element within an unordered list. The principle of sequential/linear search is that each element of the list is compared with the key in sequential order. The search begins from the starting element and proceeds until an element is found or the end of the list is encountered. If an element is found, the position of the matched element is returned. If an element is not found but the end of the list is encountered then - 1 is returned.

Program
```#include &lt stdio.h&gt
#include &lt conio.h&gt
int  Linear_Search(int[],int,int);
int Linear_Search(int a[],int n,int e)
{
int i;
for(i=0;i &lt n; i++)
if(a[i]==e)
return i;
return   -1;
}
int main()
{
int n,array,i,key,index;
printf("Enter the number of elements in the list\n");
scanf("%d",&n);
printf("\nEnter the elements of the list:\n");
for(i=0;i &lt n; i++)
scanf("%d",&array[i]);
printf("\nEnter the element to searched in the list:\n");
scanf("%d",&key);
index=Linear_Search(array,n,key);
if(index==-1)
else
printf("\nElement %d found location %d\n",key,index);
getch();
return 0;
}
```

Output

Enter the number of elements in the list
5

Enter the elements of the list:
56
78
34
45
23

Enter the element to searched in the list:
23

Element 23 found location 4

Example

For example, given listen is

Step 1:

Given List is,
The given element to be searched is 77.
The linear Search initially starts from first element i.e, 54 and computers it with the key element i.e, 77.

Step 2:

The index element is set to '0'.

Since 54 ≠ 77, 'i' moved to the next position i.e., 26.

Step 3:

The index element is set to '1'.

Since 26 ≠ 77 'i' moved to the next position element i.e, 93.
Step 4:

Now, the index element is set to 2.
Since 93 ≠ 77, 'i' is moved to the next position i.e, 17.
Step 5:

Now, the index element is set to '3'.

Now, 17 ≠ 77, 'i' is moved to next position i.e, 77.
Step 6:

Now, the index element is set to i=4.

Since 77 = 77, the current element matches with the key element at i=4.

The search is successful and the location of element index i = 4 is returned upon success.