Task: you need to find common elements that are contained in two arrays at the same time. At the output, the program should produce information of the form: {a, b, c, ..., n}, where a, b, c, n are the elements of the array. I only get (if I use the code that is commented out) to make an output of the type: {a, b, c,}, which is an error, since I give the labs through the site (progtest, if anyone knows).
Therefore, I see a new solution: I create another array in which I will store the same values of the arrays of the first two. And if you print the values of the array at that moment, when the values are saved in the array, then everything is ok. When I want to display the values of the array already in a separate cycle, following after the cycle of finding the elements, it turns out porridge.
Example:
arr1 = 1, 2, 3, 4, 5
arr2 = 2, 3, 4, 7, 8, 9
output of array data immediately after storing values in it: 2, 3, 4
output array data in a separate cycle: 5838432 2 3 4 83886085 4822
#include <iostream> using namespace std; int main() { int size1, size2; int len1, len2; cout << "Enter size of set A:\n"; cin >> size1; if (cin.fail() || size1 < 0) { cout << "Invalid input.\n"; return 0; } int arr1[size1]; len1 = sizeof(arr1) / sizeof(*arr1); cout << "Enter members of set A:\n"; for (int i = 0; i < len1; i++) cin >> arr1[i]; if (cin.fail()) { cout << "Invalid input.\n"; return 0; } cout << "Enter size of set B:\n"; cin >> size2; if (cin.fail() || size2 < 0) { cout << "Invalid input.\n"; return 0; } int arr2[size2]; len2 = sizeof(arr2) / sizeof(*arr2); cout << "Enter members of set B:\n"; for (int i = 0; i < len2; i++) cin >> arr2[i]; if (cin.fail()) { cout << "Invalid input.\n"; return 0; } int* intersect = new int[len2]; for (int i = 0; i < len1 ; i++) { for (int j = 0; j < len2; j++) { if (arr1[i] == arr2[j]) { //cout << arr1[i] << ", "; intersect[i] = arr1[i]; cout << intersect[i] << " "; } } } cout << endl; for (int i = 0; i < len2; i++) { cout << intersect[i] << " "; } return 0; }