Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Find and print all common elements in three sorted arrays of integers

C++ Array: Exercise-25 with Solution

Write a C++ program to find and print all common elements in three sorted arrays of integers.

Pictorial Presentation:

C++ Exercises: aaaaaaaa

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;
int main()
{
    int array1[] = {1, 5, 7, 8, 9, 11};
    int array2[] = {6, 8, 10, 11, 12, 16};
    int array3[] = {1, 3, 5, 6, 8, 10, 11, 17}; 
    
    int s1 = sizeof(array1)/sizeof(array1[0]);
    int s2 = sizeof(array2)/sizeof(array2[0]);
    int s3 = sizeof(array3)/sizeof(array3[0]);
    
    cout << "Original arrays: ";
    cout << "\nArray1: ";
    for (int i=0; i < s1; i++) 
    cout << array1[i] <<" ";
    cout << "\nArray2: ";
    for (int i=0; i < s2; i++) 
    cout << array2[i] <<" ";
    cout << "\nArray3: ";
    for (int i=0; i < s3; i++) 
    cout << array3[i] <<" ";
    cout <<"\nCommon elements of the said sorted arrays: ";
    int i = 0, j = 0, k = 0;
   while (i < s1 && j < s2 && k < s3)
    {
        if (array1[i] == array2[j] && array2[j] == array3[k])
         {  
             cout << array1[i] << " ";   
			 i++;
			 j++; 
			 k++;
		 }
 
        else if (array1[i] < array2[j])
             i++;
 
        else if (array2[j] < array3[k])
             j++;
 
        else
             k++;
    }
    return 0; 
}

Sample Output:

Original arrays: 
Array1: 1 5 7 8 9 11 
Array2: 6 8 10 11 12 16 
Array3: 1 3 5 6 8 10 11 17 
Common elements of the said sorted arrays: 8 11 

Flowchart:

Flowchart: Find and print all common elements in three sorted arrays of integers

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to find the first repeating element in an array of integers.
Next: Write a C++ program to find and print all unique elements of a given array of integers.

What is the difficulty level of this exercise?