# Iterative program of Linear Search

### What is linear search :

Before writing the program of Linear search first we have to understand what is Linear search. Liner search is a searching algorithm in which we search an element linearly (from starting to end of the list ).we start the searching of element from  index  0 to until we get that element . If the element is found in the list then return the index of the element otherwise return -1 . so the time complexity of the linear search is depend on the number of elements in the list .

Time Complexity of the linear search:-

Best case: In best case element will found at the index 0 . So the time complexity in best case is O(1).

Avg case :- In this time complexity is O(n). where n is number of element in the list.

Worst case: in this case element is not present in the list or at the last index of the list so we have to traverse whole list so the time complexity in this case is O(n)

Recurrence relation of Linear search:-

T(n)=T(n-1)+1

## Program of Linear search (Iterative method)

#include<stdio.h>

// iterative function for linear search
void LinearSearch(int a[],int key,int n)
{
int flag=0;
for(int i=0;i<n;i++)
{
if(a[i]==key)
{
printf("Element found at index %d",i);
flag=1;
break;
}
}
if(flag==0)
{
printf("element is not present in the array");
}
}

int main()
{
int n,key;
printf("Enter the length of the array\n");
scanf("%d",&n);
int a[n];
printf("Enter the element of the array\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the element which you want to search\n");
scanf("%d",&key);
LinearSearch(a,key,n);

return 0;
}

Output:-

Enter the length of the array
5
Enter the element of the array
1 4 3 2 5
enter the element which you want to search
4
Element found at index 1

Also check this:-