To check if two arrays are equal in C, you can use a loop to compare each element for arrays with the same elements and manually compare elements for arrays with different elements.
In this example,
arr1
and arr2
with the same elements.equal1
.equal1
is set to true
; otherwise, it's set to false
.equal1
to the console.#include <stdio.h>
#include <stdbool.h>
int main() {
int arr1[] = {1, 2, 3};
int arr2[] = {1, 2, 3};
bool equal1 = true;
int n = sizeof(arr1) / sizeof(arr1[0]);
for (int i = 0; i < n; i++) {
if (arr1[i] != arr2[i]) {
equal1 = false;
break;
}
}
printf("Arrays are equal: %s\n", equal1 ? "true" : "false");
return 0;
}
Arrays are equal: true
In this example,
arr3
and arr4
with different elements.equal2
.equal2
is set to true
; otherwise, it's set to false
.equal2
to the console.#include <stdio.h>
#include <stdbool.h>
int main() {
int arr3[] = {1, 2, 3};
int arr4[] = {3, 2, 1};
bool equal2 = true;
int n = sizeof(arr3) / sizeof(arr3[0]);
for (int i = 0; i < n; i++) {
if (arr3[i] != arr4[i]) {
equal2 = false;
break;
}
}
printf("Arrays are equal: %s\n", equal2 ? "true" : "false");
return 0;
}
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in C language with well detailed examples.