C Program to search an element in Array using "Linear Search".
Objective
Write a C program to search for an element in an Array using Linear Search.
Algorithm / Approach
- Initialize an array with random elements.
- Read the target number
nto search for. - Set
flag = 0. - Iterate through the array from index 0 to the end.
- If
a[i] == n, setflag = 1, print the index, andbreakout of the loop. - If the loop finishes and
flag == 0, print "Not found".
main.c
#include<stdio.h>
int main() {
int a[10]={10,14,19,26,27,31,33,35,42,44};
int i,n,flag=0;
printf("Enter no. to Search: ");
scanf("%d",&n);
for(i=0; i<=10; i++) {
if(a[i]==n) {
flag=1;
break;
}
}
if(flag==1) {
printf("%d found at %d pos",n,i);
}
else {
printf("Number not found.");
}
return 0;
}
Expected Output
OUTPUT : 1 Enter no. to Search: 33 33 found at 6 pos OUTPUT : 2 Enter no. to Search: 71 Number not found.
Explanation of the Program
- Linear Search (or Sequential Search) is the simplest search algorithm.
- It works exactly like searching for a specific page in a book by flipping through every single page starting from page 1. It checks every element one by one until it finds a match or runs out of elements.
Complexity
Time Complexity
O(n) - In the worst case, it checks every single element.
Space Complexity
O(1)