Comparing 2 elements in array's and counting how many of them are the same.

Just as the title states. I have the code of how to compare each array; however I'm not sure how to implement a code such that it would count the number of elements that are the same within the arrays.

Example if user array is {1,2,3,4,5}
and lottery array is {1,1,3,4,5}
It should return that there are 4 matching digits.

The code is designed as a function in which I cannot use pre-existing c++ function algorithms.

1
2
3
4
5
6
7
8
9
10
11
12
13
int matchCount(int lottery[], int user[], const int LENGTH){
int count;

for (int i=0;i<LENGTH;++i){
    for (int j=0;j<LENGTH;++j){
        while(lottery[i] == user[j]){
           
        }
    }
}

return count;
}


Now I understand that the loop itself basically examines all the possibilities for an array poisition i in the second array j.

What/how would I write the condition statements for the while loop to produce a counter.

My initial idea was this;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int matchCount(int lottery[], int user[], const int LENGTH){

	int matches = 0;

for (int i=0;i<LENGTH;++i){
    for (int j=0;j<LENGTH;++j){
        while(lottery[i] == user[j]){
			matches=1+matches;
           
        }
    }
}
cout<<matches;
return;
}


And when I do use my statement, it breaks and freezes the program. Can provide full code skeleton of the program.
Last edited on
So you're saying that if you comment out lines 3, 8, and 13, the program no longer freezes? That doesn't make any sense, those lines are trivial.
Right, which is why I'm wondering is there any other way to compare the elements of each array to each other and counting it ? And yes, without those lines the program runs and exits, with them it freezes once it enters this loop.

Figured it out, instead of while I used if, but I do not want it to count double's twice. How would I implement that?
Last edited on
Ah, what's happening is that the compiler sees that the loops do nothing when you comment out the code, so it optimizes them out. The reason it freezes is because you used the keyword while instead of the keyword if. Just a weird typo!
Topic archived. No new replies allowed.