Searching in an array involves finding whether a given element exists in the array and, if it does, at which position it is located. There are various searching algorithms, but one of the simplest and most commonly used is linear search.
Example:
#include <stdio.h>
#define MAX_SIZE 100
int linearSearch(int array[], int size, int key) {
// Iterate through the array to find the key
for (int i = 0; i < size; i++) {
// If the key is found, return its position
if (array[i] == key) {
return i;
}
}
// If the key is not found, return -1
return -1;
}
int main() {
int arr[MAX_SIZE] = {1, 2, 3, 4, 5}; // Example array
int size = 5; // Current size of the array
int key;
printf(“Enter the element to search: “);
scanf(“%d”, &key);
// Call the linearSearch function to search for the key
int position = linearSearch(arr, size, key);
// Check if the key is found
if (position != -1) {
printf(“Element found at position: %d\n”, position);
} else {
printf(“Element not found in the array.\n”);
}
return 0;
}
Explanation:
- We have a function
linearSearchthat takes the array, its size, and the key (element to search for) as parameters. - Inside
linearSearch, we iterate through the array using a loop and compare each element with the key. - If the key is found at any position, we return the index of that position.
- If the key is not found after iterating through the entire array, we return -1 to indicate that the key is not present in the array.
- In the
mainfunction, we take input from the user for the element to search (key), and then call thelinearSearchfunction. - If the
linearSearchfunction returns a valid position (i.e., not -1), we print the position where the element was found; otherwise, we print a message indicating that the element was not found in the array.