Common elements gfg in c++
To find the common elements in two arrays in C++, you can follow these steps:
Declare and initialize two arrays, let's call them
arr1
andarr2
, with the elements you want to compare.Determine the size of both arrays using the
sizeof
operator divided by the size of a single element. For example:
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
Create a loop to iterate through each element of
arr1
.Within the loop, create another loop to iterate through each element of
arr2
.Compare each element of
arr1
with every element ofarr2
using anif
statement.If a match is found, store the common element in another array or perform any desired action.
Continue the loops until all elements of
arr1
have been compared with all elements ofarr2
.
Here's an example code snippet that demonstrates finding the common elements in two arrays:
#include <iostream>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {4, 5, 6, 7, 8};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
if (arr1[i] == arr2[j]) {
std::cout << arr1[i] << " ";
break;
}
}
}
return 0;
}
In this example, the common elements between arr1
and arr2
are 4 and 5, which are printed to the console.