0% found this document useful (0 votes)
10 views

Array Applications

Uploaded by

sandster20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Array Applications

Uploaded by

sandster20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Program to merge two sorted arrays:

#include<iostream>
using namespace std;

// Merge arr1[0..n1-1] and arr2[0..n2-1] into


// arr3[0..n1+n2-1]
void mergeArrays(int arr1[], int arr2[], int n1,int n2, int arr3[])
{
int i = 0, j = 0, k = 0;

// Traverse both array


while (i<n1 && j <n2)
{
// Check if current element of first
// array is smaller than or equal to current element
// of second array. If yes, store first
// array element and increment first array
// index. Otherwise do same with second array
if (arr1[i] <= arr2[j]){

arr3[k] = arr1[i];
k++;
i++;
}
else{

arr3[k] = arr2[j];
k++;
j++;
}

// Store remaining elements of first array


while (i < n1)
{
arr3[k] = arr1[i];
k++;
i++;
}
// Store remaining elements of second array
while (j < n2)
{

arr3[k] = arr2[j];
k++;
j++;
}
}

int main()
{
int arr1[] = {2, 3, 5, 7};
int n1 = sizeof(arr1) / sizeof(arr1[0]);

int arr2[] = {2, 4, 6, 8};


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

int arr3[n1+n2];
mergeArrays(arr1, arr2, n1, n2, arr3);

cout << "Array after merging" <<endl;


for (int i=0; i < n1+n2; i++)
cout << arr3[i] << " ";

return 0;
}
Program to find common elements in an array:

#include <iostream>
# define Z 50

using namespace std;

void displayArr(int arr[], int n){


for( int i = 0; i < n; i++ ){
cout << arr[ i ] << ", ";
}
cout << endl;
}

void findCommonElement( int A[], int n, int B[], int m, int D[], int &k ) {
k = 0;
for( int i = 0; i < n; i++ ) {
for( int j = 0; j < m; j++ ) {
if( A[ i ] == B[ j ] ) {
D[ k ] = A[ i ];
k = k + 1;

}
}
}
}

int main() {
int n,m,A[Z],B[Z];
cout<<"Enter size of the first array: "<<endl;
cin>>n;
cout<<"Enter "<<n<<" elements"<<endl;
for(int i=0;i<n;i++)
{
cin>>A[i];
}
cout<<"Enter size of the second array: "<<endl;
cin>>m;
cout<<"Enter "<<m<<" elements"<<endl;
for(int i=0;i<m;i++)
{
cin>>B[i];
}
int D[ Z ];
int k = 0;

cout << "Given first array A: ";


displayArr( A, n );

cout << "Given second array B: ";


displayArr( B, m );

findCommonElement( A, n, B, m, D, k );
cout << "The common elements are: ";
displayArr( D, k );
}

You might also like