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

Given an array, we have to find the product of adjacent elements of the array using the class and object approach.
Submitted by Shubh Pachori, on September 13, 2022

Example:

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

Output: 
Product of index 0 and 9 is 10
Product of index 1 and 8 is 18
Product of index 2 and 7 is 24
Product of index 3 and 6 is 28
Product of index 4 and 5 is 30

C++ code to find the product 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];
    }
  }

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

    // for loop to add all adjacent elements of the array
    for (index_1 = 0, index_2 = 9; index_1 <= 9 / 2; index_1++, index_2--) {
      cout << "Product 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();

  cout << "\n";

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

  return 0;
}

Output:

[0]:1
[1]:3
[2]:5
[3]:7
[4]:9
[5]:2
[6]:4
[7]:6
[8]:8
[9]:10
Product of index 0 and 9 is 10
Product of index 1 and 8 is 24
Product of index 2 and 7 is 30
Product of index 3 and 6 is 28
Product of index 4 and 5 is 18

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

C++ Class and Object Programs (Set 2) »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.