Home »
C++ Programs
C++ program to find the sum 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 sum of them one array in the reverse using the class and object approach.
Example:
Input:
Input 1st Array :
[0]: 10
[1]: 9
[2]: 8
[3]: 7
[4]: 6
[5]: 5
[6]: 4
[7]: 3
[8]: 2
[9]: 1
Input 2nd Array :
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10
Output:
Reversely added array :
20 18 16 14 12 10 8 6 4 2
C++ code to find the sum 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];
}
}
// addArray() function to add two arrays
void addArray() {
// initialising variables to
// perform operations
int sum[10], index;
// for loop to add both the arrays
for (index = 0; index < 10; index++) {
sum[index] = arr1[index] + arr2[9 - index];
}
cout << "\nReversely added array :" << endl;
// for loop to print the resulted array
for (index = 0; index < 10; index++) {
cout << sum[index] << " ";
}
}
};
int main() {
// create an object
Array A;
// calling getArray() function to
// insert the arrays
A.getArray();
// calling addArray() function to
// add two arrays
A.addArray();
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]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 6
[6]: 7
[7]: 8
[8]: 9
[9]: 10
Reversely added array :
11 11 11 11 11 11 11 11 11 11
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 addArray() to store the array elements and to find sum 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 addArray() member function to find sum of two arrays one in reverse. The addArray() function contains the logic to find sum of two arrays one in reverse and printing the result.
C++ Class and Object Programs (Set 2) »