search array element in c
Here is an example code snippet in C to search for an element in an array:
#include <stdio.h>
int search(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {2, 4, 6, 8, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 6;
int result = search(arr, n, x);
if (result == -1) {
printf("Element not found in the array.\n");
} else {
printf("Element found at index %d.\n", result);
}
return 0;
}
This code defines a function search
that takes an array arr
, its size n
, and an element x
to search for. It iterates through the array and checks if each element is equal to x
. If a match is found, it returns the index of the element. If no match is found, it returns -1.
In the main
function, an example array arr
is defined, its size is calculated, and an element x
is specified to search for. The search
function is called with these parameters, and the result is stored in the variable result
. If the result is -1, it means the element was not found and a message is printed. Otherwise, the index of the element is printed.
This code can be used as a starting point to search for an element in an array in C.