Same elements of 2 arrays copied into an empty 3rd array

Hi everyone!

I am fairly new to C++ and I'm trying to learn it a little bit deeper. At the moment, I am learning how to deal with arrays.

I tried to create 2 arrays (both consisting of 5 elements that I enter) and then create a 3rd array that will consist only of elements that were in the first 2 arrays.

e.g

Array 1 = {1, 2, 7, 4, 6}
Array 2 = {2, 3, 6, 5, 4}

Now the 3rd array would be = {2, 6, 4}

The problem is, I have no idea how I should set the condition in the program to do that. At first, I thought of 2 for loops, but it doesn't really work well.

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
	const int size = 5;
	int newArraySize;

	int myArray1[size], myArray2[size], myArray3[size];

	for (int i = 0; i < size; i++)
	{
		cout << "Enter the " << i + 1 << ". number of the first array ";
		cin >> myArray1[i];
	}
	cout << endl;
	for (int i = 0; i < size; i++)
	{
		cout << "Enter the " << i + 1 << ". number of the second array ";
		cin >> myArray2[i];
	}
	cout << endl;

	for (int i = 0; i < size; i++)
	{
		cout << setw(3) << myArray1[i];
	}
	cout << endl;
	for (int i = 0; i < size; i++)
	{
		cout << setw(3) << myArray2[i];
	}
	cout << endl;


	int counter = 0;
	for (int i = 0; i < size; i++)
	{
		for (int j = 0; j < size; j++)
		{
			if (myArray1[i] == myArray2[j])
			{
				myArray3[i] = myArray2[j];
				counter++;
			}
		}
	}

	for (int i = 0; i < counter; i++)
	{
		cout << setw(3) << myArray3[i];
	}

	system("PAUSE");
	return 0;
}
Last edited on
If you change line 45 to
myArray3[counter] = myArray2[j];
then it will "work".

Once working, then some other things to think about.
- layout of your output: it is quite hard to distinguish which line of digits is which array;
- inputting elements with a separate prompt for each is a bit longwinded; just ask for the requisite number of elements and the user can input them in a single go (spaces between, for example);
- sizes of arrays are fixed (and equal); consider arrays that you can change in size as necessary (aka vectors);
- some of the in-built 'algorithms' may save you a lot of coding lines; that said, it's good for understanding to code things index-wise, and your code indentation is nice and easily readable.


Last edited on
@lastchance

Ah, I see. This particular one I wanted to do without trying to use built-in algorithms because I need to improve my "programming logic". Thank you very much for the help and also the tips.
Topic archived. No new replies allowed.