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?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1

Ref: https://bit.ly/3PWhs5N