Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two arrays in C programming language?

Tags:

arrays

c

I want to compare two different arrays which are both int. One array is static and contains numbers from 1 to 10 and second arrays asks user to enter ten different numbers and the program checks which elements from both arrays are equal.

#include <stdio.h>

int main(void) {
    int array1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int array2[10];
    int i;

    for (i = 0; i < 11; i++) {
        printf("Enter numbers: ");
        scanf("%d", &array2);
    }

    for (i = 0; i < 11; i++) {
        if (array1[i] != array2[i]) {
            printf("Not equal \n");
        } else {
            printf("They are equal. \n");
        }
    }
}

The program always say not equal even if I enter a number that is equal to a number stored in first array.

like image 700
Hassen Fatima Avatar asked Nov 19 '15 00:11

Hassen Fatima


People also ask

Can we compare 2 arrays in C?

compareArray() will compare elements of both of the array elements and returns 0 if all elements are equal otherwise function will return 1.

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do I compare two arrays to each other?

Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object. equals() .

How do you check the equality of two arrays in C?

Check if two arrays are equal or not using SortingSort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.


1 Answers

scanf("%d", &array2);

You are never updating the index of array2 when getting a value from input.

Try

scanf("%d", &array2[i]);

As for comparing, you can also use memcmp to compare memory:

memcmp(array1, array2, sizeof(array1));
like image 58
Inisheer Avatar answered Sep 28 '22 08:09

Inisheer