To check if a specified element is present in an array in C, you can use a loop to iterate through the array and compare each element.
In this example,
numbers
with values 10, 20, 30, 40, 50.for
loop to iterate through the array and compare each element with the specified element 30.found
to true; otherwise, it remains false.#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
int element = 30;
int found = 0;
for (int i = 0; i < size; ++i) {
if (numbers[i] == element) {
found = 1;
break;
}
}
printf("Element 30 is present: %s\n", found ? "true" : "false");
return 0;
}
Element 30 is present: true
In this example,
fruits
with values 'apple', 'banana', 'cherry'.for
loop to iterate through the array and compare each element with the specified element 'banana'.found
to true; otherwise, it remains false.#include <stdio.h>
#include <string.h>
int main() {
char *fruits[] = {"apple", "banana", "cherry"};
int size = sizeof(fruits) / sizeof(fruits[0]);
char *element = "banana";
int found = 0;
for (int i = 0; i < size; ++i) {
if (strcmp(fruits[i], element) == 0) {
found = 1;
break;
}
}
printf("Element 'banana' is present: %s\n", found ? "true" : "false");
return 0;
}
Element 'banana' is present: true
In this tutorial, we learned How to check if Specified Element is present in the Array in C language with well detailed examples.