Bool function to check if two arrays are identical

hello, I need to write a bool function that checks if two 1D arrays of equal length are identical. I've written a seemingly straightforward loop to check that, however in practice, the program will always return whatever Boolean value is put in place after the if statement in the code bellow. I can't figure out where i'm going wrong and any help would be greatly appreciated. thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool equalarrays(int a[], int b[], int n){
for(int i = 0; i < n; i++)  
{  
        for(int j = 0; j < n; j++)
        { 
 
                if (a[i] != b[j])
                {
                return false;
                }
        else
        return false;
        }
}  
}
Last edited on
What does identical mean? All the same numbers only, or the same numbers in the same order?
identical meaning that each index is equal to the corresponding index;
a[5] = {1,2,3,4,5}
b[5] = {1,2.3,4,5} would return true while

a[5] = {1,2,3,4,5}
b[5] = {5,1,2,3,4} would return false.

so same numbers in same order
Last edited on
Then you need only one loop.
1
2
3
4
5
6
7
8
9
10
11
bool equalarrays(int a[], int b[], int n)
{
  for (int i = 0; i < n; i++)
  {
    if (a[i] != b[i])
    {
      return false;
    }
  }
  return true;
}
thanks. that makes more sense.
1
2
3
4
#include <algorithm>

// http://en.cppreference.com/w/cpp/algorithm/equal
bool equal_arrays( const int a[], const int b[], std::size_t n ) { return std::equal( a, a+n, b ) ; }
Topic archived. No new replies allowed.