Home »
C++ Programs
C++ program to find the product of two arrays using class
Submitted by Shubh Pachori, on September 15, 2022
Problem statement
Given two arrays of integers, we to find the product to two arrays using the class and object approach.
Example:
Input:
Input 1st Array :
[0]: 2
[1]: 4
[2]: 6
[3]: 8
[4]: 2
[5]: 4
[6]: 6
[7]: 8
[8]: 10
[9]: 12
Input 2nd Array :
[0]: 1
[1]: 3
[2]: 5
[3]: 7
[4]: 9
[5]: 1
[6]: 3
[7]: 5
[8]: 7
[9]: 9
Output:
Producted Array:
2 12 30 56 18 4 18 40 70 108
C++ code to find the product of 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];
}
}
// productArray() function to
// multiply two arrays
void productArray() {
// initialising variables to
// perform operations
int temp[10], index;
// for loop to multiply both the arrays
for (index = 0; index < 10; index++) {
temp[index] = arr1[index] * arr2[index];
}
cout << "\nProducted Array:" << endl;
// for loop to print the resulted array
for (index = 0; index < 10; index++) {
cout << temp[index] << " ";
}
}
};
int main() {
// create an object
Array A;
// calling getArray() function to
// insert the arrays
A.getArray();
// calling productArray() function to
// multiply two arrays
A.productArray();
return 0;
}
Output
Input 1st Array :
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 910
[9]: 11
Input 2nd Array :
[0]: 11
[1]: 1
[2]: 2
[3]: 2
[4]: 34
[5]: 5
[6]: 6
[7]: 7
[8]: 4
[9]: 2
Producted Array:
11 2 6 8 170 30 42 56 3640 22
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 productArray() to store the array elements and to find product of 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 productArray() member function to find product of two arrays. The productArray() function contains the logic to find product of two arrays and printing the result.
C++ Class and Object Programs (Set 2) »