Enter 6 numbers into the first array: 5 3 8 2 9 4
Enter 6 numbers into the second array: 1 4 5 2 7 6
There are 3 matched numbers between the two arrays.
Note that I want it to display the amount of matched numbers, not the value of the number that is matched that it seems to be doing here. Would appreciate the help.
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int p[6], p1[6], num = 0, p2[] = {};
cout << "Enter 6 numbers into the first array: ";
for (int a=0;a<6;a++)
{
cin >> p[a];
}
cout << "Enter 6 numbers into the second array: ";
for (int a=0;a<6;a++)
{
cin >> p1[a];
}
for (int i = 0 ; i < 6; ++i)
{
for (int j = 0 ; j < 6; ++j)
{
if (p[i]==p1[j])
{
p2[num++] = p[j];
}
}
cout << "There are " << num << " matched numbers between the two arrays.";
return 0;
}
}
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
int p[6], p1[6], num = 0, p2[] = {};
cout << "Enter 6 numbers into the first array: ";
for (int a=0;a<6;a++)
{
cin >> p[a];
}
cout << "Enter 6 numbers into the second array: ";
for (int a=0;a<6;a++)
{
cin >> p1[a];
}
for (int i = 0 ; i < 6; ++i)
{
for (int j = 0 ; j < 6; ++j)
{
if (p[i]==p1[j])
{
p2[num++] = p[j];
}
} //this one was missing
}
cout << "There are " << num << " matched numbers between the two arrays.";
return 0;
}
When I input "5 3 8 2 9 4" into the first array and "1 4 5 2 7 6" into the second it displays the correct matched value of 3.
However if I input for example "9 8 7 6 5 4" into both the first and second array it displays as 12 matched values when it should be 6. Thoughts?
Do away with the p2[] array completely. (What you are doing with it may be legal in some languages, but not C++; turn the compiler error messages up and it should tell you that.) You are just incrementing num, so simply replace line 32 by num++;
However, you still need to think what you will do about mismatching numbers of repeats in your arrays. What if the first array is 1 1 1 1 1 1 and the second is 1 2 3 4 5 6 (or vice versa)?
Not sure what you mean when you say do away with the p2[] array. How do I fix this to make the code work? Sorry, I am a beginner. For mismatching numbers in that example I would like them to state as 1 matched number because both arrays would have '1'.
For the repeats, one possibility is just to store a parallel 6-element array of bools indicating which array elements (of p1[]) had already been matched up and hence couldn't be compared with again.
I presume your code is now working without repeats?
Well, to prevent an element of the inner-loop array (p2[]) being matched twice you can declare an array of bools: bool used[6] = { false }; // initialise a 6-element array of bools to false
and then your matching later would be
1 2 3 4 5
if (!used[j] && p[i]==p1[j])
{
num++;
used[j] = true;
}
There are other ways to do the problem ... and 6 is a "magic number" ... and there's a slightly simpler form of initialisation and ... tomorrow's another day!