Search code examples
arrayscfor-loopif-statementcomparison

How can I compare elements of two one-dimensional arrays with equal sets of elements according their order?


I am trying to compare elements of two arrays according their order for example:

int a[] = { 1, 2, 3 };
int b[] = { 1, 2, 4 };

Having 3 elements there is no problem with a for-loop and condition

if (a[0] == b[0] && a[1] == b[1] && a[2] == b[2])

But how can I do the same with n elements in arrays? The condition should looks like: if (a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && ... && a[n] == b[n]) but it's inappropriate.

// Comparing elements of two one-dimensional arrays with
// equal sets of elements according their order.

#include <stdio.h>

int main(void) {
    // two one-dimensional arrays with 3 elements for example
    int a[] = { 1, 2, 3 };
    int b[] = { 1, 2, 4 };

    // comparing elements:

    for (int i = 0; i < 3; i++) {
        if (a[0] == b[0] && a[1] == b[1] && a[2] == b[2]) // but if I have n - elements the problem appears
        {
            printf("all right\n");
        }
        else
        {
            printf("no all right\n");
        }
    }
}

Solution

  • Having both a for loop and an explicit comparison expression is redundant. You can solve the problem for an arbitrary number of elements with a simple function that takes both arrays and their length, compares the array elements and returns a boolean value:

    #include <stdbool.h>
    #include <stdio.h>
    
    bool compare_arrays(const int *a, const int *b, size_t n) {
        for (size_t i = 0; i < n; i++) {
            if (a[i] != b[i])
                return false;
        }
        return true;
    }
    
    int main() {
        // two one-dimensional arrays with 3 elements for example
        int a[] = { 1, 2, 3 };
        int b[] = { 1, 2, 4 };
        size_t a_len = sizeof(a) / sizeof(*a);
    
        // comparing elements:
        if (compare_arrays(a, b, a_len)) {
            printf("all right\n");
        } else {
            printf("no all right\n");
        }
        return 0;
    }