# Linear search program in C with time complexity

## Linear Search Program in C

In this Linear search program in c, we are going to learn to search for elements in an array. We will search an element of an array using for loop.

```#include<stdio.h>
int main()
{
int arr,n,i,num;
printf("n Enter Size of Array:");
scanf("%d",&n);
printf("n Enter elements of Array:");
for( i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
printf("n Enter element for searching:");
scanf("%d",&num);
for ( i = 0; i < n; i++)
{
if(arr[i]==num)
{
printf("Element found at index: %d",i);
printf("n Element found at Position: %d",i+1);
break;
}
}
if(i==n)
printf("Element not found");
return 0;
}``` Output:

Enter Size of Array: 5

Enter elements of Array:66

78

56

25

45

Enter element for searching:56

Element found at index: 2

Element found at Position: 3

## Linear search algorithm in c

Case 1: Element to be searched is present in an array

Case 2: Element to be searched is not present in an array

1. Creating for loop, initializing i = 0; i < n; i++.
2. Now, we will compare arr[i] & element to be searched.
3. If they are equal, then we will print “i”, which represents the index number. For position print “i+1”.
4. If the Element to be searched is not present in an array, then i equal to n.
5. We will compare “i” & “n”, if i equal to n then we have to print element not found

## Linear search program in C with time complexity

Best case time complexity linear search program in C: O(1)

Worst-case time complexity linear search program in C: O(n)

Average case time complexity linear search program in C: O((n+1)/2)

### When can a linear search be used?

When the array is not sorted, then we will use a linear search.

### How linear search works?

linear search works by comparing the element to be searched from all the elements present in an array. If that element is not in an array then it will print “Element not found”. If that element is present in the array then it will print index no. and position of that element in the array.

Let me know your doubts regarding the linear search program in c using for loop in the comment section.

Related posts:

Menu-Driven Program

Matrix program in c using array • Hackerrank 5* • Full Stack Developer • Masters in SEO