Common elements gfg in c++

To find the common elements in two arrays in C++, you can follow these steps:

  1. Declare and initialize two arrays, let's call them arr1 and arr2, with the elements you want to compare.

  2. 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]);
  1. Create a loop to iterate through each element of arr1.

  2. Within the loop, create another loop to iterate through each element of arr2.

  3. Compare each element of arr1 with every element of arr2 using an if statement.

  4. If a match is found, store the common element in another array or perform any desired action.

  5. Continue the loops until all elements of arr1 have been compared with all elements of arr2.

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.