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;
}
|