How to implement the all_of algorithm to check if all elements satisfy a predicate in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

/*
    all_of: Check whether ALL elements in an array satisfy 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 every element satisfies pred
        false - otherwise
 
    Idiomatic C approach:
        - Use a simple loop (fast, branch‑predictable).
        - Stop early on first failure (efficient).
        - Use function pointers for predicates.
*/
bool all_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: one element failed the predicate
        }
    }
    return true;            // All elements satisfied the predicate
}
 
/*
    Predicate:
    Check if a number is positive.
*/
bool is_positive(int x) {
    return x > 0;
}
 
/*
    Predicate:
    Check if a number is even.
*/
bool is_even(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("All positive in data1? %s\n",
           all_of(data1, size1, is_positive) ? "true" : "false");
 
    printf("All even in data2? %s\n",
           all_of(data2, size2, is_even) ? "true" : "false");
 
    printf("All positive in data3? %s\n",
           all_of(data3, size3, is_positive) ? "true" : "false");
 
    return 0;
}
 
 
 
/*
run:
 
All positive in data1? true
All even in data2? true
All positive in data3? false
 
*/

 



answered Jul 23 by avibootz
edited Jul 23 by avibootz

Related questions

...