Equality of two arrays

Write your question here.HI
Hi guys :) my task is to check equality of two arrays here is my code. I have no idea where is the problem in my code.
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
33
34
35
36
 #include "stdafx.h"
#include<iostream>
#include<algorithm>
using namespace std;
bool equality(int a[], int a1[])
{
	int x = 0;
	bool equal = false;
	for (int i = 0, j = 0; i < 6 && i < 6;){
		if (a[i] == a1[j]){
			equal = true;
			x++;
		}
		else{
			equal = false;
		}
			
	}
	if (x == 5)
		return true;
	else
		return false;
}


int _tmain(int argc, _TCHAR* argv[])
{
	int a[5] = {1,2,3,4,5};
	int a1[5] = {1,3,3,4,5};
	if (equality(a, a1))
		cout << "equals";
	else
		cout << "not equals";
	system("pause");
	return 0;
}
Last edited on
> The output of the program isnt right
¿what output do you have?
I have no output srry I will edit my question
Your code is far to complicated.

1
2
3
4
5
6
7
8
9
bool equality(int a[], int a1[])
{
  for (int i = 0; i < 6; i++)
     if (a[i] != a1[i])
       return false;
  
  return true;	
}
It isnt working properly cauz if I change in a1 3rd elemet it keep printing out equals..my task is to compare all elements in the arrays then print out true if all are same or not if there is missmatch
Last edited on
The function equality() should not assume it knows the length of the arrays. Instead pass the length as a parameter.
The code of Thomas1965 should work if adjusted accordingly.

Or, since you have included the <algorithm> header,
1
2
3
4
bool equality(int a[], int b[], unsigned int size)
{
    return std::equal( a, a+size, b);    
}
Error 1 error C4996: 'std::_Equal1': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
output of your code
my task is to compare all elements in the arrays then print out true if all are same or not if there is missmatch

There is no point is comparing all the elements once you find a mismatch. Once you find a mismatch, you know for certain the arrays are not equal. In fact, it is inefficient to do otherwise. Thomas1965's code correctly exits when the first mismatch is found.

Topic archived. No new replies allowed.