LearnFrenzy
Sign in Take a free test

Functions · Function Programs · Question 8

Count elements with a callback (function pointer) in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Write a reusable count_if() that counts the elements for which a given test function returns true.

Solution
main.c
#include <stdbool.h>
#include <stdio.h>

size_t count_if(const int *a, size_t n, bool (*pred)(int)) {
    size_t count = 0;
    for (size_t i = 0; i < n; i++)
        if (pred(a[i]))
            count++;
    return count;
}

static bool is_even(int x)     { return x % 2 == 0; }
static bool is_negative(int x) { return x < 0; }

int main(void) {
    int a[] = {4, -3, 7, -8, 0, 12, -1};
    size_t n = sizeof a / sizeof a[0];
    printf("even: %zu, negative: %zu\n", count_if(a, n, is_even), count_if(a, n, is_negative));
    return 0;
}

Output Verified by compiling and running

even: 4, negative: 3

The loop is written once; the test is passed in as a function pointer. Even numbers: 4, −8, 0, 12. Negative: −3, −8, −1. This is the same idea as the comparator you give to qsort().

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Popular