C++ program to check if two arrays are equal or not

Hello, friends in this tutorial we will write a program to check if two arrays are equal or not in C++.

An array is a collection of homogeneous i.e similar type of data stored in consecutive memory locations. Arrays come under derived data types and are very useful to store the collection of data and perform various operations on it.

Two arrays are equal if they have the same elements irrespective of the order in which they are present

For example:

A = [1, 3, 2, 5, 4]
B = [2, 4, 5, 1, 3]

Both the array A and B are equal because they have the same elements.

A = [1, 3, 2, 5, 4]
B = [3, 1, 4, 5, 6]

The arrays are not equal because the element 6 is present in B but not in A.


  1. Input both the arrays
  2. Sort both the arrays
  3. Compare the elements of both the arrays
  4. If all the elements are same return True
  5. Else return False

Check if two arrays are equal or not

Following is the C++ code snippet to check the arrays are equal or not:

 #include <bits/stdc++.h> 
using namespace std; 
/* Function to check if the arrays are equal or not */ 
bool isArrEqual(int A[], int B[], int lenA, int lenB) 
    /* check if length of array are equal
  if length is not equal means array are not equal */
    if (lenA != lenB) 
        return false; 
    /* Sort both arrays */
    sort(A, A + lenA); 
    sort(B, B + lenB); 
    /* Compare elements of the array */ 
    for (int i = 0; i < lenA; i++) 
        if (A[i] != B[i]) 
            return false; /* Elements are not same */
    /* All elements are same */ 
    return true; 
// Main function
int main() 
  int A[] = {1, 3, 2, 5, 4};
  int B[] = {2, 4, 5, 1, 3};
    int lenA = sizeof(A) / sizeof(int); 
    int lenB = sizeof(B) / sizeof(int); 
  if (isArrEqual(A, B, lenA, lenB))
    	cout<<"Arrays are equal";
    cout<<"Arrays are not equal";
  return 0; 


Arrays are equal

Leave a Reply

Your email address will not be published. Required fields are marked *