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.
compareArray() will compare elements of both of the array elements and returns 0 if all elements are equal otherwise function will return 1.
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.
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() .
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With