Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to implement the any_of algorithm to check if any element satisfies a predicate in C

1 Answer

0 votes
#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

*/

 



answered Jul 23 by avibootz

Related questions

...