In: Computer Science
Please Answer with C code and I will rate! Thank you.
Problem) Write a program that reads 20 integers and stores them
in two arrays of 10 elements
each. Then, the program should check if the two arrays have common
elements, if yes,
the program should displays the value of each common element and
its position in both arrays. Otherwise,
it should display a message and that their elements are
different.
#include<iostream>
using namespace std;
int main()
{
int i, j;
// create arrays of size 10
int arr1[10];
int arr2[10];
cout<<"Enter 10 numbers : ";
// read elements in first array
for( i = 0 ; i < 10 ; i++ )
cin>>arr1[i];
cout<<"\nEnter 10 numbers : ";
// read elements in second array
for( i = 0 ; i < 10 ; i++ )
cin>>arr2[i];
// store the number of common elements
int count = 0;
// traverse first array
for( i = 0 ; i < 10 ; i++ )
{
int index = -1;
// travserse array 2 to find common elements with i th element of array 1
for( j = 0 ; j < 10 ; j++ )
{
// if the jth element is common
if( arr1[i] == arr2[j] )
index = j;
}
// if the i th element is common
if( index != -1 )
cout<<arr1[i]<<" is common and occurs at index "<<i<<" in 1st array and index "<<index<<" in 2nd array."<<endl;
}
return 0;
}
Sample Output
