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

Submitted by Shubh Pachori, on August 22, 2022

Problem statement

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

Example:

```Input:
array[0]: 1
array[1]: 2
array[2]: 3
array[3]: 4
array[4]: 5

Output:
Product of all elements of the array is 120
```

C++ code to find the product of all 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 array[5];
// public functions
public:

// putArray() function to get the value of the array
void putArray() {
for (int index = 0; index <= 4; index++) {
cout << "array[" << index << "]:";
cin >> array[index];
}
}

// product() function to find the product of all numbers of the array
int product() {
int product = 1;

// for loop to multiply all elements of the array one by one
for (int index = 0; index <= 4; index++) {
product = product * array[index];
}

// returning the product
return product;
}
};

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

// int type variable to store the Sum of all numbers in it
int product;

// function is called by the object to store the array
A.putArray();

// product() function to multiply all elements of the array
product = A.product();

cout << "Product of all elements of the array is " << product;

return 0;
}
```

Output

```array[0]:9
array[1]:8
array[2]:7
array[3]:6
array[4]:5
Product of all elements of the array is 15120
```

Explanation

In the above code, we have created a class Array, one int type array data member array[5] to store the values of the array, and public member functions putArray() and product() to store the given values in an array and to find out the product of all elements of the array.

In the main() function, we are creating an object A of class Array, reading an integer values by the user of the array using the putArray() function, and finally calling the product() member function to find the product of all elements of the given array. The product() function contains the logic to find out the product of all elements of the given array and printing the result.

Comments and Discussions!

Student's Section
Subscribe

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