C++ program to find the sum of adjacent elements of the array using class

Submitted by Shubh Pachori, on September 13, 2022

Problem statement

Given an array, we have to find the sum of adjacent elements using the class and object approach.

Example:

```Input:
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5
[5]: 5
[6]: 4
[7]: 3
[8]: 2
[9]: 1

Output:
Sum of index 0 and 9 is 2
Sum of index 1 and 8 is 4
Sum of index 2 and 7 is 6
Sum of index 3 and 6 is 8
Sum of index 4 and 5 is 10
```

C++ code to find the sum of adjacent elements of the array using the class and object approach

```#include <iostream>
using namespace std;

// create a class
class Array {
// private data member
private:
int arr[10];

// public member functions
public:
// getArray() function to insert the array
void getArray() {
for (int index = 0; index < 10; index++) {
cout << "[" << index << "]: ";
cin >> arr[index];
}
}

// sumArray() function to find sum of the
// adjacent elements of the array
void sumArray() {
// initialising int type variables
// to perform operations
int index_1, index_2;

for (index_1 = 0, index_2 = 9; index_1 <= 9 / 2; index_1++, index_2--) {
cout << "Sum of index " << index_1 << " and " << index_2 << " is "
<< arr[index_1] + arr[index_2] << endl;
}
}
};

int main() {
// create object
Array A;

// calling getArray() function to insert array
A.getArray();

// calling sumArray() function to find sum of
// all adjacent elements of the array
A.sumArray();

return 0;
}
```

Output

```RUN 1:
[0]: 1
[1]: 3
[2]: 5
[3]: 7
[4]: 9
[5]: 2
[6]: 4
[7]: 6
[8]: 8
[9]: 10
Sum of index 0 and 9 is 11
Sum of index 1 and 8 is 11
Sum of index 2 and 7 is 11
Sum of index 3 and 6 is 11
Sum of index 4 and 5 is 11

RUN 2:
[0]: 10
[1]: 20
[2]: 15
[3]: 51
[4]: 34
[5]: 55
[6]: 66
[7]: 77
[8]: 88
[9]: 89
Sum of index 0 and 9 is 99
Sum of index 1 and 8 is 108
Sum of index 2 and 7 is 92
Sum of index 3 and 6 is 117
Sum of index 4 and 5 is 89
```

Explanation

In the above code, we have created a class Array, one int type array data members arr[10] to store the elements of the array, and public member functions getArray() and sumArray() to store the array elements and to find sum of all adjacent elements of the array.

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 sumArray() member function to find sum of all adjacent elements of the array. The sumArray() function contains the logic to find sum of all adjacent elements of the array and printing the result.