C++ Program to Find Common Array Elements

To Find common elements in two arrays in C++, you can create a program that iterates through the elements of both arrays and checks for matching elements. There are various approaches to find common elements, including using nested loops to compare every element of the first array with every element of the second array, or using data structures like sets to improve efficiency.

#include <iostream>

int main() {

    // Define the first array

    int arr1[] = {1, 3, 5, 7, 9};

    int size1 = sizeof(arr1) / sizeof(arr1[0]);

    // Define the second array

    int arr2[] = {3, 4, 5, 6, 7};

    int size2 = sizeof(arr2) / sizeof(arr2[0]);

    // Find and print common elements

    std::cout << “Common elements: “;

    for (int i = 0; i < size1; i++) {

        for (int j = 0; j < size2; j++) {

            if (arr1[i] == arr2[j]) {

                std::cout << arr1[i] << ” “;

                break; // Break the inner loop to avoid duplicate printing

            }

        }

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the program works:

  • The program starts by defining two arrays (arr1 and arr2) with some example values.
  • The sizes of the arrays are calculated using sizeof to determine the length of each array.
  • The program uses nested loops to iterate through both arrays.
    • The outer loop iterates over each element in arr1.
    • The inner loop iterates over each element in arr2.
    • If an element in arr1 matches an element in arr2, it is printed as a common element.
    • Once a common element is found, the inner loop is broken to avoid duplicate printing of the same element.
  • Finally, the program prints the common elements found in both arrays.

Leave a Reply

error: Content is protected !!