The C Program
Let's start by creating a simple C program to search for an element in an array. We'll use the linear search algorithm, which is straightforward and effective for small arrays. Here's the code:
#include <stdio.h>
int search(int array[], int size, int target) {
for (int i = 0; i < size; i++) {
if (array[i] == target) {
return i; // Return the index where the target element was found
}
}
return -1; // Return -1 to indicate that the target element was not found
}
int main() {
int arr[] = {12, 34, 56, 78, 90, 123, 45, 67, 89, 1};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 56;
int result = search(arr, size, target);
if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}
return 0;
}
In this program, we have an array arr
with ten integers, and we want to search for the element 56
. We define a function search
that takes the array, its size, and the target element as parameters. It iterates through the array and returns the index where the target element is found or -1 if it's not found.
Running the Program
Now, let's run the program and see the output:
Element 56 found at index 2.
As expected, the program has found the element 56
at index 2
in the array arr
.
Customizing the Program
You can customize this program by changing the arr
array and the target element. You can also modify the size of the array by changing the number of elements or by using user input.
Here's an example of how you can modify the program to search for a different element:
int main() {
int arr[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int result = search(arr, size, target);
if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}
return 0;
}
With these modifications, the program will search for the element 3
in a different array.
Conclusion
Searching for an element in an array is a fundamental operation in programming. In this article, we demonstrated how to perform a linear search in C to find a specific element in an array. By following the step-by-step guide and examining the code examples and outputs, you should now have a solid understanding of how to search for elements in C arrays. You can further extend and optimize this code for various applications in your C programming projects.