Here Is A C Program That Searches For A Specific Element in An Array of Size 7
Here Is A C Program That Searches For A Specific Element in An Array of Size 7
values {12, 45, 23, 78, 56, 89, 34}, and prints the index if the element is found or a
message saying it is not found:
#include <stdio.h>
int main() {
int arr[] = {12, 45, 23, 78, 56, 89, 34};
int size = 7; // Size of the array
int target;
printf("Enter the element to search for: ");
scanf("%d", &target);
int index = search_element(arr, size, target);
if (index != -1) {
printf("Element %d found at index %d.\n", target, index);
} else {
printf("Element %d not found in the array.\n", target);
}
return 0;
}
How it works:
1. The function search_element takes the array arr[], its size, and the target element
as input.
2. It uses a for loop to iterate through the array and check if the target element is present.
3. If the element is found, it returns the index of that element. If it is not found, it returns -1.
4. The main function takes the target element input from the user and calls the
search_element function.
5. Based on the return value, it either prints the index of the element or a message saying
that the element was not found.
Example Run:
Enter the element to search for: 56