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().
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!