Linear Search
Linear Search
INTRODUCTION:
Page 1
For a better understanding of the Linear search, we are going to see an
example.
Example:
Given array = {50, 90, 30, 70, 60};
Assume the search key is 30. Next, scan the array and compare each
element to the search key. The array's first element is 50, but 50 is not
equal to 30, therefore continue on to the next element. The next element
is 90, but it isn't equal to 30, so it's time to move on to the next one. The
array's next element is 30, which is the same as the search key 30, thus
returning the index of the array's current element.
The above example was the case where the search key was present in the
array. Now consider a case where the search key is not present. Let’s
assume that the search key is equal to 10. Compare each element in the
array with the search element. It fails to match with 50, 90, 30, 70, 60,
and eventually reaches the array's conclusion. As a result, return -1 or
print element is not present in the array, indicating that the search key is
not available
Page 2
Code for Linear Search in C program is given below:
#include <stdio.h>
void main()
int num;
scanf("%d", &num);
int arr[num];
scanf("%d", &arr[i]);
printf("\nEnter the key element that you would like to be searched: ");
scanf("%d", &key);
Page 3
/* Linear search starts */
if (key == arr[i] )
element_found = 1;
break;
if (element_found == 1)
else
Output:
Page 4
Explanation of Code:
Page 5
“Element is not present in array” indicating that the element was not
present.
Page 6
Conclusion
In C, Linear Search involves traversing a list or array sequentially to see
if an entry is there. The goal is to begin traversing the array and compare
items of the array one by one, starting with the first element, until a match
is discovered or the array's end is reached.
Page 7