C – Check if Array Contains Specified Element
To check if given Array contains a specified element in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for.
Examples
In the following example, we take an integer array arr
, and check if the element x = 8
is present in this array.
We use C For Loop to iterate over the elements of array, and sizeof operator to get the length of array.
main.c
</>
Copy
#include <stdio.h>
int main() {
int arr[] = {2, 4, 6, 8, 10};
int x = 8;
int arrLen = sizeof arr / sizeof arr[0];
int isElementPresent = 0;
for (int i = 0; i < arrLen; i++) {
if (arr[i] == x) {
isElementPresent = 1;
break;
}
}
if (isElementPresent) {
printf("%d is present in this array.\n", x);
} else {
printf("%d is not present in this array.\n", x);
}
return 0;
}
Output
8 is present in this array.
Program ended with exit code: 0
Conclusion
In this C Tutorial, we learned how to check if a specified element is present in this Array, with examples.