IMPLEMENTATION OF LINEAR SEARCH
Aim:
To write a C program for implementation of linear search.
Algorithm
1. Input the size of the array (n):
2. Declare an array (arr) of size n.
3. Input the array elements:
o For each index i from 0 to n-1:
Read the element and store it in arr[i].
4. Input the element to search for (x):
5. Initialize a loop for linear search:
6. For each index i from 0 to n-1:
7. If arr[i] == x, then:
8. Print "Element found at index i".
9. Stop the search (return from the function).
10. If the element is not found after checking all elements:
11. Print "Element not found in the array".
Program:
#include <stdio.h>
int linearSearch(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x)
return i; // Return the index where the element is found
}
return -1; // Return -1 if the element is not found
}
int main() {
int n, x, result;
// Input the size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
// Input the elements of the array
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input the element to search for
printf("Enter the element to search: ");
scanf("%d", &x);
// Perform linear search
result = linearSearch(arr, n, x);
// Output the result
if (result != -1) {
printf("Element found at index %d\n", result);
} else {
printf("Element not found in the array\n");
}
return 0;
}
Output:
Enter the number of elements in the array: 5
Enter 5 elements:
12
65
89
45
36
Enter the element to search: 45
Element found at index 3
Result:
Thus the C program for the implementation of linear search was successfully executed
and verified.