#include <stdio.h>
#include <stdbool.h>
/*
any_of: Check whether ANY element in an array satisfies a predicate.
Parameters:
arr - pointer to the first element of the array
n - number of elements
pred - pointer to a predicate function taking an int and returning bool
Returns:
true - if at least one element satisfies pred
false - if none satisfy the predicate
Idiomatic C approach:
- Use a simple loop (fast and predictable).
- Stop immediately when the first satisfying element is found (efficient).
- Use function pointers for flexible predicate selection.
*/
bool any_of(const int *arr, size_t n, bool (*pred)(int)) {
for (size_t i = 0; i < n; ++i) {
if (pred(arr[i])) {
return true; // Early exit: found one element satisfying the predicate
}
}
return false; // No element satisfied the predicate
}
/*
Predicate:
Check if a number is negative.
*/
bool is_negative(int x) {
return x < 0;
}
/*
Predicate:
Check if a number is odd.
*/
bool is_odd(int x) {
return (x % 2) != 0;
}
int main(void) {
int data1[] = { 3, 5, 7, 9 };
int data2[] = { 2, 4, 6, 8 };
int data3[] = { 1, -2, 3, 4 };
size_t size1 = sizeof(data1) / sizeof(data1[0]);
size_t size2 = sizeof(data2) / sizeof(data2[0]);
size_t size3 = sizeof(data3) / sizeof(data3[0]);
printf("Any negative in data1? %s\n",
any_of(data1, size1, is_negative) ? "true" : "false");
printf("Any odd in data2? %s\n",
any_of(data2, size2, is_odd) ? "true" : "false");
printf("Any negative in data3? %s\n",
any_of(data3, size3, is_negative) ? "true" : "false");
return 0;
}
/*
run:
Any negative in data1? false
Any odd in data2? false
Any negative in data3? true
*/