Linear search is a simple search algorithm that checks every element in a list until the desired element is found or the list ends.
#include<stdio.h> int linearSearch(int[], int, int); int main(){ int n, arr[50], key, pos; printf("Enter the number of elements: "); scanf("%d",&n); printf("Enter %d elements: ",n); for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } printf("Enter the element to be searched: "); scanf("%d",&key); pos = linearSearch(arr, n, key); if(pos == -1){ printf("Element not found in the array"); }else{ printf("In given array, element %d is at %d position",key, pos); } return 0; } int linearSearch(int arr[], int n, int key){ for(int i=0;i<n;i++){ if(arr[i]==key){ return i; } } return -1; }Sample Input1 and Output1:
Enter the number of elements: 5
Enter 5 elements: 1 4 6 8 9
Enter the element to be searched: 6
In given array, element 6 is at 2 position
Sample Input2 and Output2:Enter 5 elements: 1 4 6 8 9
Enter the element to be searched: 6
In given array, element 6 is at 2 position
Enter the number of elements: 5
Enter 5 elements: 1 4 6 8 9
Enter the element to be searched: 7
Element not found in the array
Enter 5 elements: 1 4 6 8 9
Enter the element to be searched: 7
Element not found in the array