#include <stdio.h>
#include <stdbool.h>
/*
none_of: Check whether NO 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 no element satisfies pred
false - if at least one element satisfies pred
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 none_of(const int *arr, size_t n, bool (*pred)(int)) {
for (size_t i = 0; i < n; ++i) {
if (pred(arr[i])) {
return false; // Early exit: found an element satisfying the predicate
}
}
return true; // No element satisfied the predicate
}
/*
Predicate:
Check if a number is zero.
*/
bool is_zero(int x) {
return x == 0;
}
/*
Predicate:
Check if a number is greater than 10.
*/
bool greater_than_10(int x) {
return x > 10;
}
int main(void) {
int data1[] = { 3, 5, 7, 9 };
int data2[] = { 0, 4, 6, 8 };
int data3[] = { 1, 2, 3, 11 };
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("None zero in data1? %s\n",
none_of(data1, size1, is_zero) ? "true" : "false");
printf("None zero in data2? %s\n",
none_of(data2, size2, is_zero) ? "true" : "false");
printf("None >10 in data3? %s\n",
none_of(data3, size3, greater_than_10) ? "true" : "false");
return 0;
}
/*
run:
None zero in data1? true
None zero in data2? false
None >10 in data3? false
*/