Home »
C++ Programs
C++ program to merge two arrays using class
Submitted by Shubh Pachori, on September 15, 2022
Problem statement
Given two arrays, we to merge them using the class and object approach.
Example:
Input:
Input 1st Array :
[0]: 1
[1]: 3
[2]: 5
[3]: 7
[4]: 9
[5]: 11
[6]: 1
[7]: 3
[8]: 5
[9]: 7
Input 2nd Array :
[0]: 2
[1]: 4
[2]: 6
[3]: 8
[4]: 10
[5]: 12
[6]: 14
[7]: 16
[8]: 18
[9]: 20
Output:
Merged Array:
1 3 5 7 9 11 1 3 5 7 2 4 6 8 10 12 14 16 18 20
C++ code to merge two arrays using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Array {
// private data members
private:
int arr1[10];
int arr2[10];
// public member functions
public:
// getArray() function to insert arrays
void getArray() {
cout << "Input 1st Array :" << endl;
for (int index = 0; index < 10; index++) {
cout << "[" << index << "]:";
cin >> arr1[index];
}
cout << "\nInput 2nd Array :" << endl;
for (int index = 0; index < 10; index++) {
cout << "[" << index << "]: ";
cin >> arr2[index];
}
}
// mergeArray() function to merge two arrays
void mergeArray() {
// initialising variables to perform operations
int temp[20], index;
// for loop to merge both arrays
for (index = 0; index < 20; index++) {
// if condition for 1st array
if (index < 10) {
temp[index] = arr1[index];
}
// else condition for 2nd array
else {
temp[index] = arr2[index - 10];
}
}
cout << "\nMerged Array: " << endl;
// for loop to print merged array
for (index = 0; index < 20; index++) {
cout << temp[index] << " ";
}
}
};
int main() {
// create an object
Array A;
// calling getArray() function to
// insert the arrays
A.getArray();
// calling mergeArray() function to
// merge two arrays
A.mergeArray();
return 0;
}
Output
Input 1st Array :
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10
Input 2nd Array :
[0]: 10
[1]: 9
[2]: 8
[3]: 7
[4]: 6
[5]: 5
[6]: 4
[7]: 3
[8]: 21
[9]: 9
Merged Array:
1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 21 9
Explanation
In the above code, we have created a class Array, two int type array data members arr1[10] and arr2[10] to store the elements of the array, and public member functions getArray() and mergeArray() to store the array elements and to merge two arrays.
In the main() function, we are creating an object A of class Array, reading the inputted array by the user using getArray() function, and finally calling the mergeArray() member function to merge two arrays. The mergeArray() function contains the logic to merge two arrays and printing the result.
C++ Class and Object Programs (Set 2) »