Professional Documents
Culture Documents
Linear Search
Linear Search
Linear Search
Overview
The Linear Search algorithm in C sequentially checks each element of the list until
the key element is found or the entire list has been traversed. Therefore, it is
known as a sequential search.
Linear Search is the most basic method of searching an element from a list. It is
also known as sequential search, as it sequentially checks each element of the list
until the key element is found or the entire list has been traversed. It uses
conditional statements and relational operators to find whether the given element
is present in the list or not. It is easy to learn and implement.
Compare every element of the list with the key element starting from the leftmost
end of the list.
If any element of the list matches with the key, return the index of that element.
If the entire list has been traversed and none of the elements matched with the
key, then return -1, which specifies the key element is not present in the list.
#include<stdio.h>
int main() {
scanf("%d", &size);
scanf("%d", &arr[i]);
scanf("%d", &key);
if (index < size) // condition to check whether previous loop partially traversed or
not
printf("Key element found at index %d", index); // printing the index if key found
else
return 0;
Output:
Explanation:
✔️Take the input of the element to search for i.e. key element.
✔️The array will be traversed with the help of a loop from 0 to size-1.
✳️Inside the loop, Apply a condition that whether the current element is equal to
the key element or not
✳️If the current element matches with the key element, then get out of the loop
using a break statement, and if is not matched, the condition keeps checking the
elements until the end of the array.
✔️After the cursor gets out of the loop, check whether the previous loop traversed
the array partially or not with the help of a condition that the index of the previous
loop is less than the size of the array or not.
✔️If the condition returns true, then print the index of the key element.
✔️If the condition returns false, then print the key element not found.