How to implement the all_of_equal algorithm to check if all elements are equal to a value in C

1 Answer

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

/*
    all_of_equal: Check whether ALL elements in an array
                  are equal to a specific value.

    Parameters:
        arr     - pointer to the first element of the array
        n       - number of elements
        value   - the value to compare against

    Returns:
        true  - if every element equals 'value'
        false - otherwise

    Idiomatic C approach:
        - Use a simple loop (fast and predictable).
        - Stop immediately when the first mismatch is found (efficient).
*/
bool all_of_equal(const int *arr, size_t n, int value) {
    for (size_t i = 0; i < n; ++i) {
        if (arr[i] != value) {
            return false;   // Early exit: found a mismatch
        }
    }
    return true;            // All elements matched
}

int main(void) {
    int data1[] = { 5, 5, 5, 5 };
    int data2[] = { 3, 3, 4, 3 };
    int data3[] = { 7, 7, 7, 7 };

    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 equal to 5 in data1? %s\n",
           all_of_equal(data1, size1, 5) ? "true" : "false");

    printf("All equal to 3 in data2? %s\n",
           all_of_equal(data2, size2, 3) ? "true" : "false");

    printf("All equal to 7 in data3? %s\n",
           all_of_equal(data3, size3, 7) ? "true" : "false");

    return 0;
}



/*
run:

All equal to 5 in data1? true
All equal to 3 in data2? false
All equal to 7 in data3? true

*/

 



answered Jul 24 by avibootz

Related questions

...