how to see if all elements of two arrays are equal

i'm stuck on how to compare all the elements of two arrays to see if they're equal. the code I've written only seems to check the first element of the both arrays and doesn't actually check all the elements....for example if the first array ("simons_array") equals 7 7 7 and the second array (users_array) equals 7 8 8 it still says they're equal...tried rewriting this a million ways and googled/youtubed the subject still can't find anything that makes sense to me...would really appreciate any help or suggestions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 	for(int i=0; i<arraysize; i++)
	{
		for(int j=0; j<arraysize; j++)
		{
			if(users_array[i] == simons_array[j])
			{
				cout << "\n\n\nCORRECT!\tBeing added to the winners file!!!\n\n";
				cout << "Do you want to see the contents of winners.txt (enter Y or N)?" << endl;

			}

			else
			{
				
				cout << "sorry, real numbers and your answer are: " << endl;
				for(int x=0; x<arraysize; x++)
				cout << simons_array[x] << " ";
				cout << "\n";
				for(int y=0; y<arraysize; y++)
				cout << users_array[y] << " ";

			}
			break;
		}
		break;
	}
Last edited on
the code I've written only seems to check the first element of the both arrays and doesn't actually check all the elements


Why are you breaking out of your loops?
Lets see how we would do this on paper first.

Check each letter and see if they are equal. The first time it finds two letters not equal then they are not equal.

We can write a basic function like this (hard to tell what type of array you are using so I'll give two examples cstring and std::string )



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//cstring

bool equal( char array1[] , array2[] )
{
    for( int i = 0; array1[i] && array2[i]; ++i )
    {
        if( array1[i] != array2[i] )
        {
            return( false );
        }
    }
    return( true );
}

//std::string

bool equal( std::string array1 , std::string array2 )
{
    const int size = array1.size();
    if( size != array2.size() ) 
    {
        return( false );
    }
    for( int i = 0; i < size; ++i )
    {
        if( array1[i] != array2[i] )
        {
            return( false );
        }
    }
    return( true );
}


There are other ways also without using the pre-made compare algorithms or the two basic methods I showed above such as using pointers or iterators.

*edit also a lot of people don't like multiple return statements because they think it can be confusing just like some people don't like break statements. A way to go around this is to define a variable then assign it the true or false value then return that variable.
Last edited on
Topic archived. No new replies allowed.