Home »
C++ Programs
C++ program to find the product of two arrays one in reverse 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 one in reverse using the class and object approach.
Example:
Input 1st Array :
[0]: 8
[1]: 5
[2]: 3
[3]: 5
[4]: 8
[5]: 0
[6]: 9
[7]: 6
[8]: 1
[9]: 7
Input 2nd Array :
[0]: 9
[1]: 9
[2]: 8
[3]: 1
[4]: 5
[5]: 9
[6]: 2
[7]: 8
[8]: 2
[9]: 4
Output:
Reversely producted array :
32 10 24 10 72 0 9 48 9 63
C++ code to find the product of two arrays one in reverse 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 product[10], index;
// for loop to multiply both the arrays
for (index = 0; index < 10; index++) {
product[index] = arr1[index] * arr2[9 - index];
}
cout << "\nReversely producted array :" << endl;
// for loop to print the resulted array
for (index = 0; index < 10; index++) {
cout << product[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]: 91
[9]: 10
Input 2nd Array :
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10
Reversely producted array :
10 18 24 28 30 30 28 24 182 10
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 one in reverse.
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 one in reverse. The productArray() function contains the logic to find product of two arrays one in reverse and printing the result.
C++ Class and Object Programs (Set 2) »